#!/usr/bin/env python3
"""crossfetch — animated rainbow Chi-Rho (☧) dashboard for the terminal.
The Chi-Rho (Labarum) — Greek letters Chi (Χ) + Rho (Ρ), the monogram of
"Christos" that Constantine adopted.
Usage:
crossfetch [rose|aurora|burst|ring|rain|both] live dashboard ($CROSS_MODE)
crossfetch --fetch [secs] symbol + system specs, symbol glowing in place
crossfetch --logo [symbol] print a static rainbow Chi-Rho (fastfetch logo)
crossfetch --sync-fastfetch render fastfetch.template.jsonc with the
active theme's accents into
~/.config/fastfetch/config.jsonc
crossfetch --feast [id] force a feast's colors/emblem/verse and run
its burst once (id defaults to today's feast,
else easter_day); see liturgy.FEAST_DEFS for
valid ids (christmas, epiphany, ash_wednesday,
palm_sunday, good_friday, easter_day,
ascension, pentecost, all_saints). This is an
explicit replay: it ignores CROSS_LITURGY and
CROSS_FEAST, which only gate the automatic
(unrequested) season/feast behavior.
crossfetch -h | --help show this help and exit
Behaviour:
* Runs in the terminal's ALTERNATE screen buffer, so it never touches
scrollback. Cursor + screen are restored on exit (end, Ctrl-C, keypress).
* DEFAULT MODE IS `rose`: a cathedral rose window blooms open around the
symbol — rings of petals in Fibonacci counts, counter-rotating, unfold
outward from a gilded heart, colored straight from the Rose Pine accents
(gold heart, love/rose petals, iris rim) — while loose petals drift down
the star-filled night sky around it. The symbol stays lit in front, at
the window's heart. Stateless like aurora — pure periodic functions of
(cell, time) — and it needs no ricefx.
* `aurora` (the former default): a wavy arc of northern lights hangs in the
upper third of a dark, star-filled sky, rays of varying length reaching
down from it and fading into the dark, while the full Rose Pine poster
rainbow (teal -> gold -> rose -> love -> iris) slides through the band
and waves of brightness run along it. Most of the screen stays night
sky — the aurora is a subject on it, not a fill. Stateless too, so it
renders identically everywhere.
* `burst` (the former default): the symbol charges, detonates, and a TWO-COLOUR
shockwave floods outward from behind it — concentric bands alternating
between two Rose Pine accents (gold and iris by default) with a dark
trough between them, so the fill reads as banded rather than as one flat
wash. Further shockwaves keep pulsing out through the flood, brightening
the cells they cross, and the symbol stays lit in front inside a DEEP rim
that cuts it out of the fill. The symbol takes the same two accents in
this mode, so the whole frame is one palette.
* `ring` keeps the orbiting comet, `rain` the falling trails, `both`
alternates. Those keep the full poster rainbow too.
* It runs until you press a key, or until $CROSS_TIMEOUT seconds elapse
(0/empty = until keypress).
* The splash shows symbol + effect + verse only — system specs come from
`--fetch` afterwards, which also keeps startup instant.
Env:
CROSS_MODE rose | aurora | burst | ring | rain | both (default: rose)
CROSS_TIMEOUT seconds before auto-exit (default: 0 = until keypress)
CROSS_SYMBOL chi | orthodox | jerusalem | ichthys | kali | skull | star | dove | thorns
(default: chi; the zshrc startup block rotates through
these between launches)
CROSS_BURST two Rose Pine accent names, comma separated, for the burst
flood and its symbol (default: today's liturgical season or
feast, via liturgy.py; falls back to gold,iris when that is
unavailable or CROSS_LITURGY is off). Any of
love gold rose pine foam iris text subtle muted.
CROSS_LITURGY off | 0 | no disables all liturgical coloring (season and
feast alike); the splash falls back to gold,iris
CROSS_FEAST off | 0 | no disables feast emblem + one-shot animation
only (season coloring still applies)
CROSS_GLOW seconds of --fetch animation before it settles: a crest
sweeps once across the whole block (logo AND specs), then
the logo keeps shimmering for the remainder
(default: 1.6; 0 disables, keypress skips)
CROSS_FPS frame rate ceiling for the live dashboard (default: 60)
NO_COLOR any value skips every animation (the --logo output is
machine-consumed by fastfetch and stays colored)
Static logo:
crossfetch --logo [symbol] print for fastfetch (arg overrides env)
"""
import datetime
import json
import math
import os
import random
import re
import select
import shutil
import subprocess
import sys
import time
import unicodedata
try: # the shared purple-shimmer palette, shipped alongside
import ricefx # (sys.path[0] is this script's own directory)
except ImportError: # absent -> burst degrades to ring, nothing else changes
ricefx = None
try:
import liturgy # same directory as ricefx
except Exception:
liturgy = None
try: # Unix-only bits for "press any key to exit"
import termios
import tty as _ttymod
except ImportError: # exotic platform — dashboard exits via timeout/Ctrl-C only
termios = None
_ttymod = None
# ── Chi-Rho shape ───────────────────────────────────────────────────────────
def _build_chi_rho():
"""Procedurally draw the Chi-Rho into a '#'/' ' grid (keeps strokes clean)."""
W, H = 21, 21
g = [[" "] * W for _ in range(H)]
cx = W // 2 # central axis (the Rho's vertical stroke)
for y in range(H): # Rho stem
g[y][cx] = "#"
bowl = { # Rho loop (the "P" bowl), opens right
1: range(cx, cx + 5), 2: [cx + 4, cx + 5], 3: [cx + 5],
4: [cx + 5], 5: [cx + 4, cx + 5], 6: range(cx, cx + 5),
}
for y, xs in bowl.items():
for x in xs:
if 0 <= x < W:
g[y][x] = "#"
cy, span = 12, 9 # Chi (the "X"), centered low
for k in range(-span, span + 1):
y = cy + k
if 0 <= y < H:
for x in (cx + k, cx - k):
if 0 <= x < W:
g[y][x] = "#"
return ["".join(r) for r in g]
# ── Orthodox cross shape ────────────────────────────────────────────────────
def _build_orthodox_cross():
"""Russian Orthodox (three-bar) cross ☦ — short top bar (titulus), long
main bar (patibulum), slanted footrest (suppedaneum, viewer's left raised)."""
W, H = 21, 21
g = [[" "] * W for _ in range(H)]
cx = W // 2
for y in range(H): # vertical stem
g[y][cx] = "#"
for x in range(cx - 3, cx + 4): # top bar
g[3][x] = "#"
for x in range(cx - 7, cx + 8): # main bar
g[7][x] = "#"
for k in range(-5, 6): # slanted footrest
y = 15 if k == 0 else 15 + (abs(k) + 1) // 2 * (1 if k > 0 else -1)
g[y][cx + k] = "#"
return ["".join(r) for r in g]
# ── Jerusalem cross shape ───────────────────────────────────────────────────
def _build_jerusalem():
"""Jerusalem cross — central cross potent (T-barred ends) with a small
Greek crosslet in each quadrant. The five crosses together stand for the
five wounds of Christ."""
W, H = 21, 21
g = [[" "] * W for _ in range(H)]
cx = cy = 10
for y in range(3, 18): # potent: vertical + horizontal
g[y][cx] = "#"
for x in range(3, 18):
g[cy][x] = "#"
for d in range(-2, 3): # the four T-bars
g[3][cx + d] = g[17][cx + d] = "#"
g[cy + d][3] = g[cy + d][17] = "#"
for qy, qx in ((5, 5), (5, 15), (15, 5), (15, 15)): # quadrant crosslets
for d in range(-2, 3):
g[qy][qx + d] = "#"
g[qy + d][qx] = "#"
return ["".join(r) for r in g]
# ── Ichthys shape ───────────────────────────────────────────────────────────
def _build_ichthys():
"""Ichthys (ΙΧΘΥΣ) — the fish. Two arcs meeting at the nose and crossing
over into the tail."""
import math as m
W, H = 21, 21
g = [[" "] * W for _ in range(H)]
cy, body = 10, 15
for x in range(body): # the two arcs of the body
off = round(5.5 * m.sin(m.pi * x / (body - 1)))
g[cy - off][1 + x] = "#"
g[cy + off][1 + x] = "#"
for k in range(1, 5): # arcs cross into the tail
g[cy - k][body + k] = "#"
g[cy + k][body + k] = "#"
g[cy][7] = "#" # the eye
return ["".join(r) for r in g]
# ── Skull shape ─────────────────────────────────────────────────────────────
def _build_skull():
"""Pixel skull — hacker's memento mori. Elliptic cranium, hollow eyes,
nasal notch, four teeth."""
import math as m
W, H = 21, 21
g = [[" "] * W for _ in range(H)]
cx = 10
for y in range(15): # cranium ellipse
dy = (y - 7) / 7.5
half = int(8 * m.sqrt(max(0.0, 1 - dy * dy)))
for x in range(cx - half, cx + half + 1):
g[y][x] = "#"
for ey in range(6, 10): # eye sockets
for ex in (5, 6, 7, 13, 14, 15):
g[ey][ex] = " "
for y, xs in ((11, [10]), (12, [9, 10, 11])): # nasal notch
for x in xs:
g[y][x] = " "
for y in range(15, 19): # jaw with teeth gaps
for x in range(6, 15):
g[y][x] = "#" if x not in (8, 11) else " "
return ["".join(r) for r in g]
# ── Star of Bethlehem ───────────────────────────────────────────────────────
def _build_star():
"""Four long rays + short diagonals, center widened — the star of the
Nativity (Christmas, Epiphany)."""
W = H = 21
g = [[" "] * W for _ in range(H)]
c = 10
for k in range(-9, 10): # vertical + horizontal rays
g[c + k][c] = "#"
g[c][c + k] = "#"
for k in range(-4, 5): # short diagonal rays
g[c + k][c + k] = "#"
g[c + k][c - k] = "#"
for y in (c - 1, c + 1): # widened center
for x in (c - 1, c, c + 1):
g[y][x] = "#"
return ["".join(r) for r in g]
# ── Dove (Holy Spirit) ──────────────────────────────────────────────────────
def _build_dove():
"""Descending dove, wing raised — Pentecost. Hand-drawn; tweak freely."""
return [
" ",
" ## ",
" #### ",
" ###### ",
" ####### ",
" # ####### ",
" ## ####### ",
" #### ######### ",
" ############## # ",
" ############### ",
" ############ ",
" ######### ",
" ###### ",
" #### ",
" ## ",
]
# ── Crown of thorns ─────────────────────────────────────────────────────────
def _build_thorns():
"""Woven ring with outward spikes — Good Friday."""
W = H = 21
g = [[" "] * W for _ in range(H)]
c = 10
for deg in range(0, 360, 4): # the ring, radius 7
rad = math.radians(deg)
g[round(c + 7 * math.sin(rad))][round(c + 7 * math.cos(rad))] = "#"
for deg in range(15, 360, 45): # spikes poking outward
rad = math.radians(deg)
for r in (8, 9):
y = round(c + r * math.sin(rad))
x = round(c + r * math.cos(rad))
if 0 <= y < H and 0 <= x < W:
g[y][x] = "#"
return ["".join(r) for r in g]
# ── Kali dragon shape ───────────────────────────────────────────────────────
# The official Kali Linux dragon, traced from kali.org's kali-dragon-icon.svg
# (white dragon extracted, rendered as quadrant blocks: 2x2 pixels per cell).
# Quadrant art keeps the thin tendrils that a plain block grid destroys.
KALI = [
" ▝▀▀▀▀▀▀██▙▄▄▖",
" ▀▀▜█▙▄▖",
" ▝▀██▄",
" ▗▄▄▄▄▄▄▄▄▄▄▖▝█",
" ▄▄▟█▀▀▀▀▀▀▀▀▀▀▀▀▀▌▐▖",
" ▝▀▘ ▗▄▄▄▄▝▌",
" ▗▄███▀▀▀▀ ▙ ▖",
" ▗▄█▛▀▘ ▐▙▖ ▝▚",
" ▄█▀▘ ▗█████▄▄▖ ▜▖",
" ▄▛▀ ▟█▛▀▀▀▀▜█▙▙ ▜▖",
" ▗▛▘ ▐█▘ ▝▀██▖",
" █▌ ▀██▖",
" ▗█ ▐█▙",
" ▐█ ▀█▄",
" ▐█ ▜▌",
" ▝█▖",
" █▙",
" ▝█▙",
" ▜█▙▄",
" ▝▜██████▙▄▄▖",
" ▀▀▀▀▀▜████▄▖",
" ▝▜▙▞▜▙",
" ▝█▖▝▙",
" ▝▙ ▝▙",
" ▝▌ ▝▌",
" ▜ ▜",
" ▝▌ ▝",
" ▙",
" ▐",
" ▐"
]
CHI_RHO = _build_chi_rho()
ORTHODOX = _build_orthodox_cross()
SYMBOLS = {
"chi": CHI_RHO,
"orthodox": ORTHODOX,
"jerusalem": _build_jerusalem(),
"ichthys": _build_ichthys(),
"kali": KALI,
"skull": _build_skull(),
"star": _build_star(),
"dove": _build_dove(),
"thorns": _build_thorns(),
}
MASK = CHI_RHO
CW = len(MASK[0]) # symbol width (mask cells)
CH = len(MASK) # symbol height (mask cells)
GLYPH = "█"
PX = 2 # terminal columns per '#' mask cell — cells are ~1:2, so
# two columns make each cell a square pixel like the print
IS_ART = False # True for pre-drawn character art (kali): the glyphs ARE
# the pixels, 1 column each, no doubling and no checker
SW = CW * PX # symbol width in terminal columns
ALIASES = {"cross": "orthodox", "☦": "orthodox", "☧": "chi", "fish": "ichthys",
"ixoye": "ichthys", "dragon": "kali", "bethlehem": "star", "spirit": "dove"}
def set_symbol(name):
"""Select which symbol MASK holds. $CROSS_SYMBOL: any key of SYMBOLS."""
global MASK, CW, CH, IS_ART, SW
name = (name or "chi").strip().lower()
MASK = SYMBOLS.get(ALIASES.get(name, name), CHI_RHO)
CW = max(len(r) for r in MASK)
CH = len(MASK)
IS_ART = any(c not in "# " for r in MASK for c in r)
SW = CW * (1 if IS_ART else PX)
# ── color helpers ───────────────────────────────────────────────────────────
# Rose Pine only — the poster flow (teal top → gold → rose → purple →
# blue bottom) built purely from official base-dark accents, so the symbol never
# clashes with the rest of the rice. Both ends are pine, so the cyclic
# animation wraps without a seam. Edit these tuples to recolor everything.
PALETTE = [
(49, 116, 143), # pine
(156, 207, 216), # foam
(246, 193, 119), # gold
(235, 188, 186), # rose
(235, 111, 146), # love
(196, 167, 231), # iris
(49, 116, 143), # pine (bottom)
]
# The stops pal()/grad() actually read. Burst mode swaps in a two-accent set
# (see use_burst_palette) so the symbol matches the flood it is standing in;
# every other mode, and the static fastfetch logo, keeps the poster rainbow.
STOPS = PALETTE
def pal(t):
"""Map t (cyclic, 0..1) to a color smoothly interpolated across STOPS."""
n = len(STOPS)
x = (t % 1.0) * n
i = int(x)
f = x - i
a, b = STOPS[i % n], STOPS[(i + 1) % n]
return tuple(int(a[k] + (b[k] - a[k]) * f) for k in range(3))
def grad(t):
"""Map t (clamped, 0..1) across STOPS end to end — no wraparound.
The static logo uses this so the top is teal and the bottom is blue,
exactly like the poster; pal() stays cyclic for the animation."""
t = max(0.0, min(1.0, t))
x = t * (len(STOPS) - 1)
i = int(x)
f = x - i
a, b = STOPS[i], STOPS[min(i + 1, len(STOPS) - 1)]
return tuple(int(a[k] + (b[k] - a[k]) * f) for k in range(3))
def cell_t(i, j):
"""Gradient position of mask cell (row i, col j) — vertical, plus a drift
away from the center axis so the X arms run ahead of the stem hue. The
poster is left-right symmetric, hence abs() rather than a raw diagonal."""
cx = CW // 2
return (i + 0.4 * abs(j - cx)) / (CH - 1 + 0.4 * cx)
def checker(i, j):
"""Subtle per-pixel mosaic shading — alternate cells fade a touch toward
the background, giving flat strokes the hand-tiled texture of the print."""
return 1.0 if (i + j) % 2 == 0 else 0.88
OVERLAY = (38, 35, 58) # Rosé Pine overlay — all fades sink into this dark surface
def scale(rgb, v):
"""Fade a color toward the Rosé Pine overlay background (v=1 full accent,
v=0 gone) for ring glow, rain trails and mosaic shading."""
v = max(0.0, min(1.0, v))
return tuple(int(OVERLAY[k] + (rgb[k] - OVERLAY[k]) * v) for k in range(3))
def lerp(a, b, t):
"""Blend rgb a→b by t (0..1) — the reveal crest mixes toward iris."""
t = max(0.0, min(1.0, t))
return tuple(int(a[k] + (b[k] - a[k]) * t) for k in range(3))
IRIS = (196, 167, 231) # iris — THE purple, reserved for ripple crests
REVEAL_SECS = 0.45 # one-shot ripple reveal of the symbol (kept < 0.5s)
def fg(rgb):
return f"\033[38;2;{rgb[0]};{rgb[1]};{rgb[2]}m"
def bg_code(rgb):
return f"\033[48;2;{rgb[0]};{rgb[1]};{rgb[2]}m"
RESET = "\033[0m"
HIDE, SHOW = "\033[?25l", "\033[?25h"
ALT, UNALT = "\033[?1049h", "\033[?1049l"
_ANSI = re.compile(r"\x1b\[[0-9;]*m")
def at(row, col): # 1-based cursor move
return f"\033[{row};{col}H"
def visible_len(s):
return len(_ANSI.sub("", s))
# ── static logo (for fastfetch) ─────────────────────────────────────────────
def cell_color(i, j, phase=None):
"""Color of mask cell (i, j). phase=None is the static poster gradient
(top teal, bottom blue, end to end); a phase makes it the cyclic wave, so
the same cells can be repainted in place to animate the printed logo."""
t = cell_t(i, j)
rgb = grad(t) if phase is None else pal(t + phase)
return rgb if IS_ART else scale(rgb, checker(i, j))
def logo_row(i, phase=None):
"""One rendered row of the logo. Glyph positions never depend on phase,
so rows painted at different phases overlay each other exactly."""
out, last = [], None
for j, c in enumerate(MASK[i]):
if c == " " or (not IS_ART and c != "#"):
if last is not None:
out.append(RESET)
last = None
out.append(" " if IS_ART else " " * PX)
continue
code = fg(cell_color(i, j, phase))
if code != last:
out.append(code)
last = code
out.append(c if IS_ART else GLYPH * PX)
return "".join(out).rstrip() + RESET
def print_logo():
sys.stdout.write("\n".join(logo_row(i) for i in range(CH)) + "\n")
# ── fastfetch config sync ───────────────────────────────────────────────────
def _readable(c, bg, text):
"""Nudge a role toward the theme's text color if it would be illegible
as foreground on this background (the pine-on-dark rule, generalized)."""
def lum(x):
r, g, b = (v / 255 for v in x)
return 0.2126 * r + 0.7152 * g + 0.0722 * b
if abs(lum(c) - lum(bg)) < 0.22:
return tuple(int(a + (t - a) * 0.5) for a, t in zip(c, text))
return c
def sync_fastfetch(tpl_path=None, out_path=None):
"""Render ~/.config/crossfetch/fastfetch.template.jsonc with the active
theme's accents into ~/.config/fastfetch/config.jsonc. Returns 0/1."""
tpl = tpl_path or os.path.expanduser(
"~/.config/crossfetch/fastfetch.template.jsonc")
out = out_path or os.path.expanduser("~/.config/fastfetch/config.jsonc")
try:
with open(tpl, encoding="utf-8") as fh:
text = fh.read()
except OSError as e:
print(f"crossfetch: cannot read template: {e}", file=sys.stderr)
print(" expected at ~/.config/crossfetch/fastfetch.template.jsonc",
file=sys.stderr)
return 1
if ricefx is None:
print("crossfetch: ricefx module missing", file=sys.stderr)
return 1
acc = ricefx.ACCENTS[ricefx.theme()]
bg = acc["base"]
missing = []
# Structural roles are ALLOWED to sit close to the background (the bar
# groove uses highlightMed precisely because it is dim) — only text-ish
# roles get the legibility nudge. Without this exemption the rose-pine
# round-trip would rewrite highlightMed and break byte-identity.
neutral = {"base", "surface", "overlay",
"highlightLow", "highlightMed", "highlightHigh"}
def sub(m):
name = m.group(1)
c = acc.get(name)
if c is None:
missing.append(name)
return m.group(0)
if name not in neutral:
c = _readable(c, bg, acc["text"])
return "38;2;%d;%d;%d" % c
rendered = re.sub(r"\{\{(\w+)\}\}", sub, text)
if missing:
print(f"crossfetch: unknown roles in template: {sorted(set(missing))}",
file=sys.stderr)
return 1
tmp = out + ".tmp"
with open(tmp, "w", encoding="utf-8") as fh:
fh.write(rendered)
os.replace(tmp, out)
return 0
# ── fetch: logo + specs side by side, logo glowing in place afterwards ───────
# fastfetch draws the logo itself, which leaves nothing addressable afterwards:
# to animate the art we have to know exactly which rows and columns it occupies.
# So the composition happens here instead — fastfetch is asked for the info
# block ALONE and it is placed to the right of our own logo, at a column we
# chose. The logo then owns rows 0..CH-1 of columns 1..SW for the glow.
LOGO_PAD_TOP = 1 # blank line above the art (matches config.jsonc)
LOGO_PAD_RIGHT = 4 # columns between the art and the info block
GLOW_SPEED = 0.42 # laps of the palette per second while glowing
_COL_G = re.compile(r"\x1b\[(\d+)G")
def _shift_columns(line, off):
"""Push fastfetch's absolute column stops right by off.
The key/value alignment is done with CHA (\\e[13G — "go to column 13"),
which is absolute. Indenting the line without rewriting those codes puts
every value back at column 13, on top of the logo.
"""
return _COL_G.sub(lambda m: "\x1b[%dG" % (int(m.group(1)) + off), line)
def compose_fetch():
"""[lines] — the logo and the fastfetch info block, side by side."""
info = capture_info()
off = SW + LOGO_PAD_RIGHT
rows = []
for r in range(max(LOGO_PAD_TOP + CH, len(info))):
i = r - LOGO_PAD_TOP
left = logo_row(i) if 0 <= i < CH else ""
right = _shift_columns(info[r], off) if r < len(info) else ""
if not right:
rows.append(left)
continue
rows.append(left + " " * max(1, off - visible_len(left)) + right)
return rows
# ── sweeping a crest across already-coloured text ────────────────────────────
# The specs block cannot simply be recoloured the way the logo can: its colours
# carry meaning. Gold is a key, love is a disk at 81%, the bar has a filled
# segment and a groove. Replacing them with a shimmer would animate away the
# information. So the crest only overrides the handful of columns it is
# standing on, and every other column keeps whatever the line originally said —
# which means tracking the line's own SGR state as we walk it, and restoring
# that state on the far side of the crest.
SWEEP_SECS = 0.55 # one pass, left edge to right edge
SWEEP_HALF = 3 # columns either side of the crest centre that light up
_ESC_ANY = re.compile(r"\x1b\[[0-9;?]*[a-zA-Z]")
_RESET_SGR = re.compile(r"^\x1b\[0*m$")
def _char_width(ch):
if unicodedata.combining(ch):
return 0
return 2 if unicodedata.east_asian_width(ch) in "WF" else 1
def _sweep_line(line, centre, crest, mid):
"""Re-emit `line` with a crest of light centred on visible column `centre`.
Returns the line unchanged when the crest is nowhere near it, so untouched
rows cost nothing.
"""
out = []
state = [] # the SGR codes the line itself has established so far
col = 0
lit = None # the override currently in effect, if any
i = 0
n = len(line)
while i < n:
if line[i] == "\x1b":
m = _ESC_ANY.match(line, i)
if not m:
i += 1
continue
esc = m.group(0)
i = m.end()
if esc.endswith("m"):
if _RESET_SGR.match(esc):
state = []
else:
state.append(esc)
elif esc.endswith("G"):
col = int(esc[2:-1] or 1) - 1
out.append(esc)
lit = None # the line just restated its own colour
continue
ch = line[i]
i += 1
d = col - centre
if d < 0:
d = -d
want = crest if d <= 1 else (mid if d <= SWEEP_HALF else None)
if want is not None:
if want != lit:
out.append(want)
lit = want
elif lit is not None:
# Back off the crest: restore whatever the line was saying here.
out.append(RESET)
out.extend(state)
lit = None
out.append(ch)
col += _char_width(ch)
if lit is not None:
out.append(RESET)
out.extend(state)
return "".join(out)
def repaint_block(lines, up, centre, crest, mid):
"""Repaint every row of the printed block with the crest at `centre`."""
buf = ["\x1b7", "\x1b[%dA" % up]
last = len(lines) - 1
for n, line in enumerate(lines):
buf.append("\r")
buf.append(_sweep_line(line, centre, crest, mid) if centre is not None
else line)
if n < last:
buf.append("\n")
buf.append("\x1b8")
sys.stdout.write("".join(buf))
sys.stdout.flush()
def repaint_logo(up, phase):
"""Redraw the logo rows in place, `up` lines above the cursor.
Saves and restores the cursor around the repaint (DECSC/DECRC) and only
ever moves upward into lines that have already been printed, so nothing
scrolls and scrollback keeps whatever the last painted frame was.
"""
buf = ["\x1b7", "\x1b[%dA" % up]
for i in range(CH):
buf.append("\r")
buf.append(logo_row(i, phase))
if i < CH - 1:
buf.append("\n")
buf.append("\x1b8")
sys.stdout.write("".join(buf))
sys.stdout.flush()
def fetch(glow_secs):
"""Print the fetch, sweep a crest across all of it, then shimmer the logo.
Two phases, because the two halves of the block want different treatment.
The specs are information, so they get a crest passing over them once and
are then left alone in their real colours. The logo is decoration, so it
can keep moving for as long as the glow lasts.
"""
lines = compose_fetch()
sys.stdout.write("\n".join(lines) + "\n")
sys.stdout.flush()
if glow_secs <= 0 or not sys.stdout.isatty() or os.environ.get("NO_COLOR"):
return
try:
cols, rows = os.get_terminal_size()
except OSError:
return
# If the block is taller than the window it has already scrolled, and the
# rows we would move up to are not the rows we printed.
if len(lines) + 1 > rows:
return
up = len(lines) - LOGO_PAD_TOP
tty_fd, old = _raw_tty()
budget = 1.0 / max(15.0, min(120.0, _fps()))
# The crest is legible over both the dark ground and the specs' own colours
# because it comes from the TEXT ramp, which is the one ricefx guarantees
# keeps contrast with the background.
crest = fg(ricefx.ramp(0.0, kind="text")) if ricefx else fg((232, 213, 255))
mid = fg(ricefx.ramp(0.10, kind="text")) if ricefx else fg((196, 167, 231))
# The crest travels the terminal's width, not the longest line's: the specs
# place themselves with absolute column stops, so a line's character count
# says nothing about how far right it actually reaches.
span = cols
block_up = len(lines)
sys.stdout.write(HIDE)
try:
start = time.time()
swept = False
while True:
frame_start = time.time()
elapsed = frame_start - start
if elapsed >= glow_secs:
break
if elapsed < SWEEP_SECS:
# Phase 1: one crest, off the left edge and out past the right,
# so every column is crossed exactly once.
centre = -SWEEP_HALF + (span + 2 * SWEEP_HALF) * (elapsed / SWEEP_SECS)
repaint_block(lines, block_up, centre, crest, mid)
else:
if not swept:
repaint_block(lines, block_up, None, crest, mid) # true colours
swept = True
repaint_logo(up, elapsed * GLOW_SPEED)
if key_pressed(tty_fd, max(0.0, budget - (time.time() - frame_start))):
break
except KeyboardInterrupt:
pass
finally:
# Settle: the specs back to exactly what they said, the logo back to
# the static poster gradient.
repaint_block(lines, block_up, None, crest, mid)
repaint_logo(up, None)
sys.stdout.write(SHOW + RESET)
sys.stdout.flush()
_restore_tty(tty_fd, old)
# ── frame buffer (left panel only — info is drawn separately to the right) ────
class Panel:
# Merge two changed spans separated by this many unchanged cells rather
# than paying for a second cursor-move escape to skip over them.
GAP = 4
def __init__(self, w, h):
self.w, self.h = w, h
self.prev = None
self.clear()
BLANK = (" ", "")
def clear(self):
# List multiplication, not a per-cell comprehension: this runs once a
# frame over the whole terminal and the tuple is immutable, so sharing
# one instance across every cell is safe (cells are replaced, never
# mutated) and measurably cheaper on a large window.
blank = self.BLANK
self.cells = [[blank] * self.w for _ in range(self.h)]
def put(self, x, y, ch, color):
if 0 <= y < self.h and 0 <= x < self.w:
self.cells[y][x] = (ch, color)
def flush(self):
"""Repaint only what changed since the last frame.
A flooded screen is a smooth gradient, so run-length coding buys almost
nothing — adjacent cells genuinely differ. What DOES repeat is the same
cell between consecutive frames: the bands drift slowly enough that
most cells hold their quantized color from one frame to the next, so
diffing against the previous frame is where the bandwidth is saved.
"""
prev = self.prev
buf = []
for y, row in enumerate(self.cells):
prow = prev[y] if prev is not None else None
x = 0
while x < self.w:
if prow is not None and row[x] == prow[x]:
x += 1
continue
start = x
gap = 0
while x < self.w:
if prow is not None and row[x] == prow[x]:
gap += 1
if gap > self.GAP:
break
else:
gap = 0
x += 1
end = x - gap # trim the trailing gap
buf.append(at(y + 1, start + 1))
last = None
for cx in range(start, end):
ch, color = row[cx]
if color != last:
buf.append(color or RESET)
last = color
buf.append(ch)
buf.append(RESET)
if buf:
sys.stdout.write("".join(buf))
sys.stdout.flush()
self.prev = [r[:] for r in self.cells]
def draw_symbol(scr, sx, sy, phase, reveal=1.0):
"""Gradient symbol, drawn last so it sits in front of the effect.
Same poster gradient as the static logo, slowly cycled by phase.
While reveal < 1 a one-shot purple ripple sweeps outward from the center:
cells the wavefront hasn't reached stay hidden and the crest itself glows
iris, so the symbol surfaces from behind an expanding wave."""
ccx, ccy = (CW - 1) / 2.0, (CH - 1) / 2.0
front = reveal * (math.hypot(ccx, ccy) + 3.0)
for i, line in enumerate(MASK):
for j, c in enumerate(line):
if c == " " or (not IS_ART and c != "#"):
continue
crest = 0.0
if reveal < 1.0:
d = math.hypot(j - ccx, i - ccy)
if d > front:
continue # the wave hasn't arrived yet
crest = max(0.0, 1.0 - (front - d) / 2.5)
if IS_ART:
color = pal(cell_t(i, j) + phase)
if crest:
color = lerp(color, IRIS, crest)
scr.put(sx + j, sy + i, c, fg(color))
else:
color = scale(pal(cell_t(i, j) + phase), checker(i, j))
if crest:
color = lerp(color, IRIS, crest)
code = fg(color)
for k in range(PX):
scr.put(sx + j * PX + k, sy + i, GLYPH, code)
def draw_ring(scr, ccx, ccy, rx, ry, elapsed, phase):
"""Faint static ring + a glowing point with a comet trail orbiting it."""
for a in range(0, 360, 6):
r = math.radians(a)
x = round(ccx + rx * math.cos(r))
y = round(ccy + ry * math.sin(r))
scr.put(x, y, "·", fg(scale(pal(a / 360.0 + phase), 0.35)))
t = elapsed * 2.6
for k in range(12):
a = t - k * 0.15
x = round(ccx + rx * math.cos(a))
y = round(ccy + ry * math.sin(a))
v = max(0.2, 1.0 - k / 12.0)
scr.put(x, y, "●" if k == 0 else "•", fg(scale(pal(a / (2 * math.pi) + phase), v)))
# ── burst: purple shockwave that floods the terminal ─────────────────────────
# The default splash. A charge, a detonation behind the symbol, then an
# expanding front that leaves the screen FILLED with drifting purple bands.
# All color comes from ricefx so the shimmer matches every other tool.
CHARGE_SECS = 0.15 # symbol pulls the glow inward before it goes off
FLOOD_SPEED = 46.0 # cells/sec — how fast the fill front eats the screen
EDGE_SOFT = 2.0 # cells of feathering ahead of the front
BAND_LEN = 17.0 # radial cells per lap of the ramp. ONE lap is both
# accents, two troughs and the neutrals between them, so
# it has to be wide — and widening it is what makes the
# accents read as ribbons rather than as a wash, since
# only 2 of the ramp's 12 stops are accents.
BAND_SPEED = 0.68 # bands drift outward this fast (laps/sec)
WAVE_PERIOD = 1.00 # seconds between secondary shockwaves
WAVE_SPEED = 62.0 # secondary shockwaves outrun the flood front
WAVE_THICK = 1.7 # thin + hard-falloff: a crack of light, not a smear
WAVE_FALLOFF = 3 # exponent on the crest profile — higher = sharper
EMBERS_PER_WAVE = 34
TURB1, TURB2 = 2.8, 1.6 # radial warp amplitudes — buckle the rings into lobes
# Global dimmer on the flood. 1.0 — the ramp carries the darkness itself, in
# real palette neutrals. Turning this down shades the accents toward the
# background, which in Rose Pine means desaturating them out of the palette
# (see the note in use_burst_palette); it is here as an escape hatch, not as
# the brightness control. To calm the flood, widen BAND_LEN instead: that
# gives the neutrals more of the lap and the accents less, which is the
# palette-safe way to spend less screen on colour.
FLOOD_LEVEL = 1.0
CREST_LIFT = 0.95 # how much of the way to full a crest lifts a cell
# The symbol's shadow, as a multiplier on the flood level, one ring per entry.
# NOT an opaque rim drawn over the flood: an opaque outline is only thin where
# the silhouette is convex, and on an open lattice like the Jerusalem cross
# every interior gap touches the outside, so a 1-cell rim covers a third of the
# symbol's bounding box and reads as a plate behind the art. Dimming the flood
# instead keeps the bands and their colour running through the gap — the
# symbol casts a shadow into the blast rather than punching a hole in it.
RIM_SHADOW = (0.42, 0.74)
# Density ladder: sparse dots at the feathered edge up to solid fill inside.
DENSITY = ((0.86, "█"), (0.62, "▓"), (0.38, "▒"), (0.16, "░"), (0.04, "·"))
# X is halved before hypot() so a circle in cell space renders as a circle on
# screen — terminal cells are about twice as tall as they are wide.
ASPECT = 0.5
def _glyph(v):
for threshold, ch in DENSITY:
if v >= threshold:
return ch
return None
def _quantize(rgb, step=6):
"""Snap a color to a coarse grid so neighbouring cells compare equal."""
return (rgb[0] // step * step, rgb[1] // step * step, rgb[2] // step * step)
# Quantization buckets for the flood. A full-screen truecolor gradient at one
# escape per cell is ~350KB a frame on a large window — several MB/s, which is
# what makes a terminal animation stutter, not the arithmetic. Snapping the
# RAMP POSITION (rather than the resulting rgb) to a fixed number of steps caps
# the whole screen at a few dozen distinct colors: neighbouring cells collapse
# into runs, and the escape strings themselves come from a cache.
POS_STEPS = 24 # distinct colors around one lap of the ramp
# Raised from 16 because a lap now spans BOTH accents, so
# per-hue resolution had halved. Not raised further: the
# step grid is also what the frame diff rides on, and the
# cost is steeply non-linear. Measured on a 200x50 panel in
# steady state, 60fps: 16 steps 4.6MB/s, 24 steps 4.8MB/s,
# 32 steps 9.3MB/s — past ~24 a step is so much finer than
# the per-frame drift that nearly every cell crosses a
# boundary every frame and the diff stops skipping anything.
FADE_STEPS = 10 # distinct feather levels at the leading edge
CREST_STEPS = 6 # distinct shockwave-crest levels
_STYLE_CACHE = {}
# ── the two-accent burst ramp ────────────────────────────────────────────────
# ricefx's own ramp is purple end to end — right for a shimmer crossing a line
# of text, wrong for filling a whole screen, where every stop being a tint of
# one hue reads as a flat wash (and its crest, spark #e8d5ff, is bright enough
# to swallow the symbol standing in it).
#
# This ramp instead runs A -> trough -> B -> trough -> A , read cyclically, so
# consecutive radial bands alternate accent. It is SYMMETRIC about both crests,
# which is what makes the wrap seamless: the last stop and the first are the
# same distance from the A crest, so a band crossing the seam does not jump.
BURST_STOPS = None # built once, after the theme is known
BURST_A = BURST_B = None
CREST_COL = None # what a passing shockwave pulls a cell toward
DEFAULT_PAIR = ("gold", "iris")
STATE_DIR = os.path.expanduser("~/.local/state/crossfetch")
FORCED_FEAST = None # set by --feast for replays; wins over everything
def _flag_off(var):
return os.environ.get(var, "").strip().lower() in ("off", "0", "no")
def _today_feast():
if liturgy is None or _flag_off("CROSS_LITURGY") or _flag_off("CROSS_FEAST"):
return None
try:
return liturgy.feast(datetime.date.today())
except Exception:
return None
def _active_feast():
return FORCED_FEAST if FORCED_FEAST is not None else _today_feast()
def _liturgy_pair():
"""Accent-role pair for today: forced feast > feast > season. None when
liturgical coloring is off or the liturgy module is missing."""
if FORCED_FEAST is not None:
return FORCED_FEAST.roles
if liturgy is None or _flag_off("CROSS_LITURGY"):
return None
try:
f = _today_feast()
return f.roles if f else liturgy.season(datetime.date.today()).roles
except Exception:
return None
def _shown_path():
return os.path.join(STATE_DIR, "shown.json")
def _feast_unseen(f):
try:
with open(_shown_path()) as fh:
data = json.load(fh)
except Exception:
data = {}
return f.id not in data.get(str(datetime.date.today().year), [])
def _mark_feast_seen(f):
# Never let a state-write failure (read-only $HOME, disk full, permission
# denied, ...) crash the splash — worst case the animation just replays
# on the next launch.
try:
os.makedirs(STATE_DIR, exist_ok=True)
try:
with open(_shown_path()) as fh:
data = json.load(fh)
except Exception:
data = {}
year = str(datetime.date.today().year)
data.setdefault(year, [])
if f.id not in data[year]:
data[year].append(f.id)
tmp = _shown_path() + ".tmp"
with open(tmp, "w") as fh:
json.dump(data, fh)
os.replace(tmp, _shown_path())
except Exception:
pass
def _cross_burst_pair():
"""The two accent names from $CROSS_BURST if it names a valid pair, else
None. Parsed identically to _pair() so both call sites agree on what
counts as "explicitly set"."""
raw = os.environ.get("CROSS_BURST", "")
names = [n.strip().lower() for n in raw.replace(" ", ",").split(",") if n.strip()]
valid = [n for n in names if n in ricefx.ACCENTS[ricefx.theme()]]
if len(valid) >= 2:
return valid[0], valid[1]
return None
def use_season_stops():
"""Point STOPS at a gradient built from today's liturgical pair, so the
static --logo and the --fetch glow follow the season. Explicit
$CROSS_BURST always wins over the season/feast pair (same rule --burst
itself follows). No-op when neither is set and liturgical coloring is
off. Ring/rain keep the poster rainbow."""
if ricefx is None:
return
pair = _cross_burst_pair() or _liturgy_pair()
if not pair:
return
acc = ricefx.ACCENTS[ricefx.theme()]
if pair[0] not in acc or pair[1] not in acc:
return
a, b = acc[pair[0]], acc[pair[1]]
global STOPS
STOPS = [a, lerp(a, b, 0.35), lerp(a, b, 0.7), b, lerp(b, a, 0.5), a]
# The shoulder each crest falls off through on its way to the dark stops. Real
# palette members, picked by temperature so a warm crest does not run through a
# cool tone (or vice versa) on its way down — that crossing is what reads as a
# dirty edge on the band.
WARM = {"gold", "love", "rose"}
def _shoulder(name):
pick = "rose" if name in WARM else "subtle"
if pick == name: # the accent IS its own shoulder
pick = "gold" if name == "rose" else "muted"
return ricefx.accent(pick)
def _pair():
"""The two accent names from $CROSS_BURST, falling back to today's
liturgical pair, falling back to gold,iris."""
cb = _cross_burst_pair()
if cb:
return cb
lp = _liturgy_pair()
if lp and all(n in ricefx.ACCENTS[ricefx.theme()] for n in lp):
return lp[0], lp[1]
return DEFAULT_PAIR
def use_burst_palette():
"""Resolve the accent pair and build every color the burst needs.
Deferred rather than done at import: ricefx.accent() calls theme(), which
reads the environment, and importing a module must not depend on it.
"""
global BURST_STOPS, BURST_A, BURST_B, CREST_COL, STOPS
if BURST_STOPS is not None:
return
na, nb = _pair()
a, b = ricefx.accent(na), ricefx.accent(nb)
# EVERY stop is a literal Rose Pine hex — nothing here is a blend toward
# the background. That is the whole design: the palette has no dark
# saturated tones, so "a dimmer gold" does not exist in it. Fading gold
# #f6c177 toward base #191724 to calm the flood down produces #8b6f47,
# a khaki that appears nowhere in Rose Pine, and a screen full of it reads
# exactly like the mud it is.
#
# So the flood is not dimmed at all. The accents stay at FULL strength and
# the ramp spends most of its lap in the palette's own neutrals, which
# makes each accent a narrow ribbon over a dark ground rather than a wash.
# Brightness is controlled by AREA, not by shading.
# highlightMed, not highlightHigh: #403d52 against #26233a keeps the ground
# genuinely dark, so the two accents are the only lit things in the frame.
# highlightHigh #524f67 is light enough to read as a third band.
hl_high = ricefx.accent("highlightMed")
overlay = ricefx.accent("overlay")
sa, sb = _shoulder(na), _shoulder(nb)
# Two identical halves, one per accent: a single accent stop, then straight
# down into a long flat dark run. ONE stop in five carries colour, which is
# what makes each band a ribbon over ground rather than a field of it.
#
# No shoulder stop here, though the symbol still uses one. A shoulder next
# to the crest doubles the width of the lit band, and when the shoulder is
# close to the accent in hue and luminance the two merge into one wide
# smear — iris #c4a7e7 beside subtle #908caa did exactly that, so the gold
# half read as a ribbon and the iris half as a wash. Interpolating a crest
# straight into highlightHigh does pass through a desaturated version of
# the accent, but it crosses it in about a cell, which is an edge rather
# than a colour anyone reads.
#
# The doubled overlay stop is a held trough: without a flat run the ramp is
# always on its way somewhere and the screen pulses as one mass instead of
# resolving into separate bands.
BURST_A, BURST_B = a, b
BURST_STOPS = ([a, hl_high, overlay, overlay, hl_high]
+ [b, hl_high, overlay, overlay, hl_high])
# A shockwave BRIGHTENS what it crosses on a dark terminal and DARKENS it
# on a light one — contrast runs the opposite way. The old fixed deep-iris
# crest was the dawn answer applied to a base-dark rice, which is why the
# pulses read as passing shadows instead of blasts.
#
# `text` is the palette's extreme in both directions (#e0def4 on dark,
# #575279 on dawn), so this stays a Rose Pine colour rather than a
# hand-picked white.
CREST_COL = ricefx.accent("text")
# Symbol takes the same two accents, at full strength and with no neutral
# stops at all — it is the subject, so it stays the brightest thing on
# screen while the flood spends most of its lap in the dark. Cyclic: the
# last shoulder runs back into crest A with no seam.
STOPS = [a, sa, b, sb]
def _bramp(t):
"""Sample the two-accent burst ramp at cyclic position t."""
n = len(BURST_STOPS)
x = (t % 1.0) * n
i = int(x)
f = x - i
a, b = BURST_STOPS[i % n], BURST_STOPS[(i + 1) % n]
return (int(a[0] + (b[0] - a[0]) * f),
int(a[1] + (b[1] - a[1]) * f),
int(a[2] + (b[2] - a[2]) * f))
def _flood_style(pos, v, crest):
"""Cached escape string for one flooded cell."""
key = (int(pos * POS_STEPS) % POS_STEPS,
int(v * FADE_STEPS), int(crest * CREST_STEPS))
style = _STYLE_CACHE.get(key)
if style is None:
col = _bramp(key[0] / POS_STEPS)
if key[2]:
col = ricefx.mix(col, CREST_COL, key[2] / CREST_STEPS * 0.75)
style = fg(ricefx.sink(col, key[1] / FADE_STEPS))
_STYLE_CACHE[key] = style
return style
class Burst:
"""Shockwave state: the flood front, the pulses riding it, and the embers.
The per-cell geometry is STATIC — the blast centre never moves — so radius
and the turbulence harmonics are computed once here instead of once per
cell per frame. That removes a sqrt and two atan2/sin calls from the inner
loop of a full-screen redraw, which is the whole reason the flood could
not hold a frame rate on a large window.
"""
def __init__(self, ccx, ccy, w, h, shadow=None):
self.ccx, self.ccy = ccx, ccy
self.w, self.h = w, h
self.shadow = shadow if shadow is not None else [1.0] * (w * h)
# Furthest corner, in the same halved-x space the drawing uses.
self.reach = max(
math.hypot((x - ccx) * ASPECT, y - ccy)
for x in (0, w - 1) for y in (0, h - 1)
)
# Flat row-major tables, indexed y * w + x.
n = w * h
self.D = [0.0] * n # radius, in halved-x space
# sin/cos of the two turbulence harmonics, so the per-frame phase can
# be applied with the angle-addition identity — four multiplies per
# cell instead of two transcendental calls.
self.S3 = [0.0] * n
self.C3 = [0.0] * n
self.S5 = [0.0] * n
self.C5 = [0.0] * n
sin, cos, atan2, sqrt = math.sin, math.cos, math.atan2, math.sqrt
i = 0
for y in range(h):
dy = y - ccy
for x in range(w):
dx = (x - ccx) * ASPECT
self.D[i] = sqrt(dx * dx + dy * dy)
a = atan2(dy, dx)
self.S3[i] = sin(3 * a)
self.C3[i] = cos(3 * a)
self.S5[i] = sin(5 * a)
self.C5[i] = cos(5 * a)
i += 1
self.waves = [] # birth times of secondary shockwaves
self.embers = [] # (angle, speed, birth, hue)
self.next_wave = CHARGE_SECS
def update(self, t):
if t >= self.next_wave:
self.waves.append(t)
self.next_wave = t + WAVE_PERIOD
for k in range(EMBERS_PER_WAVE):
# Alternate the hue so the debris carries both accents out
# ahead of the fill, not just the one the front happens to be.
self.embers.append((random.uniform(0, math.tau),
random.uniform(0.55, 1.5) * WAVE_SPEED,
t, k & 1))
# Retire anything that has left the screen, so the lists stay short.
self.waves = [w for w in self.waves
if (t - w) * WAVE_SPEED <= self.reach + WAVE_THICK]
self.embers = [e for e in self.embers
if (t - e[2]) * e[1] <= self.reach + 2]
def draw_burst(scr, burst, elapsed):
"""Fill the panel with the shockwave. Called before the symbol is drawn."""
burst.update(elapsed)
ccx, ccy = burst.ccx, burst.ccy
front = FLOOD_SPEED * max(0.0, elapsed - CHARGE_SECS)
cells = scr.cells
# Charge: a tight glow collapsing onto the symbol before it detonates.
if elapsed < CHARGE_SECS:
k = elapsed / CHARGE_SECS
halo = (1.0 - k) * 9.0 + 2.0
D = burst.D
w = burst.w
style = fg(_quantize(ricefx.sink(BURST_STOPS[0], k * 0.7)))
g = _glyph(k * 0.7)
if g:
for y in range(scr.h):
row = cells[y]
base = y * w
for x in range(scr.w):
if abs(D[base + x] - halo) < 1.4:
row[x] = (g, style)
return
wave_radii = [(elapsed - w) * WAVE_SPEED for w in burst.waves]
# Turbulence phases, advanced once per frame rather than per cell. Kept
# slow: fast turbulence shifts every cell's color every frame, which both
# defeats the frame diff and makes the flood churn instead of breathe.
tw1, tw2 = elapsed * 0.32, elapsed * -0.21
c1, s1 = math.cos(tw1), math.sin(tw1)
c2, s2 = math.cos(tw2), math.sin(tw2)
# Bind everything the inner loop touches to a local — attribute and global
# lookups are the dominant cost once the trig is precomputed.
D, S3, C3, S5, C5 = burst.D, burst.S3, burst.C3, burst.S5, burst.C5
shadow = burst.shadow
W, H = scr.w, scr.h
cache = _STYLE_CACHE
style_for = _flood_style
glyph_for = _glyph
band_len, band_drift = BAND_LEN, elapsed * BAND_SPEED
soft, thick, flood_level = EDGE_SOFT, WAVE_THICK, FLOOD_LEVEL
pstep, fstep, cstep = POS_STEPS, FADE_STEPS, CREST_STEPS
no_waves = not wave_radii
for y in range(H):
row = cells[y]
base = y * W
for x in range(W):
i = base + x
d = D[i]
edge = front - d
if edge < -soft:
continue # front has not arrived yet
# Feather the leading edge from nothing up to a solid fill. Glyph
# DENSITY comes from the feather alone, so the interior stays a
# solid block fill; COLOUR level is that feather held down to
# FLOOD_LEVEL, so the bands read as bands without out-shouting the
# symbol. Splitting the two is what lets the fill be dim and solid
# at the same time — scaling one value did both at once and turned
# the interior into sparse dither the moment it was dimmed.
dens = 1.0 if edge >= 0 else 1.0 + edge / soft
sh = shadow[i]
v = dens * flood_level * sh
# Bands are sampled on RADIUS so they push outward, but perfectly
# concentric rings read as a dartboard. Warping the radius by angle
# buckles them into lobes — a blast front, not a bullseye.
# sin(3a + tw1) expanded, so the per-cell sines are table lookups.
warp = (TURB1 * (S3[i] * c1 + C3[i] * s1)
+ TURB2 * (S5[i] * c2 + C5[i] * s2))
pos = (d + warp) / band_len - band_drift
crest = 0.0
if not no_waves:
for r in wave_radii: # secondary shockwaves, brighter
dr = r - d
if dr < 0.0:
dr = -dr
if dr < thick:
c = (1.0 - dr / thick) ** WAVE_FALLOFF
if c > crest:
crest = c
if crest:
# Pulses ride up to full — but still inside the shadow, so a
# shockwave sweeping past the symbol does not erase the shadow
# it is casting.
v += (1.0 - v) * crest * CREST_LIFT * sh
# Only the feathered edge fades out; the interior stays fully filled.
g = glyph_for(dens)
if g is None:
continue
key = (int(pos * pstep) % pstep, int(v * fstep), int(crest * cstep))
style = cache.get(key)
if style is None:
style = style_for(pos, v, crest)
row[x] = (g, style)
# Embers: debris flung out ahead of the fill, so the blast has grain.
hues = (BURST_A, BURST_B)
for angle, speed, birth, hue in burst.embers:
age = elapsed - birth
r = age * speed
v = max(0.0, 1.0 - r / (burst.reach + 1e-6)) ** 1.5
if v <= 0.05:
continue
x = round(ccx + math.cos(angle) * r / ASPECT)
y = round(ccy + math.sin(angle) * r)
scr.put(x, y, "•" if v > 0.55 else "·",
fg(_quantize(ricefx.sink(hues[hue], min(1.0, v * 1.6)))))
_RIM_CACHE = {}
def _rim_cells(sx, sy):
"""The one-cell outline hugging the symbol, computed once per position.
Static geometry — the symbol never moves — so this is a setup cost, not a
per-frame one.
"""
hit = _RIM_CACHE.get((sx, sy))
if hit is not None:
return hit
occupied = set()
for i, line in enumerate(MASK):
for j, c in enumerate(line):
if c == " " or (not IS_ART and c != "#"):
continue
if IS_ART:
occupied.add((sx + j, sy + i))
else:
for k in range(PX):
occupied.add((sx + j * PX + k, sy + i))
if not occupied:
_RIM_CACHE[(sx, sy)] = ()
return ()
x0 = min(p[0] for p in occupied) - 1
x1 = max(p[0] for p in occupied) + 1
y0 = min(p[1] for p in occupied) - 1
y1 = max(p[1] for p in occupied) + 1
# Flood the margin ring inward. Whatever it reaches is outside the
# silhouette; enclosed gaps are not reached and so are never rimmed.
outside = set()
stack = [(x, y0) for x in range(x0, x1 + 1)]
stack += [(x, y1) for x in range(x0, x1 + 1)]
stack += [(x0, y) for y in range(y0, y1 + 1)]
stack += [(x1, y) for y in range(y0, y1 + 1)]
while stack:
p = stack.pop()
if p in outside or p in occupied:
continue
if not (x0 <= p[0] <= x1 and y0 <= p[1] <= y1):
continue
outside.add(p)
x, y = p
stack.append((x - 1, y))
stack.append((x + 1, y))
stack.append((x, y - 1))
stack.append((x, y + 1))
# Successive rings outward, each hugging everything claimed so far. Only
# cells the outside flood fill reached are eligible, so an enclosed gap is
# never counted as adjacent-to-outside.
rings = []
claimed = set(occupied)
for _ in RIM_SHADOW:
ring = tuple(p for p in outside
if p not in claimed
and ((p[0] - 1, p[1]) in claimed or (p[0] + 1, p[1]) in claimed
or (p[0], p[1] - 1) in claimed
or (p[0], p[1] + 1) in claimed))
rings.append(ring)
claimed.update(ring)
_RIM_CACHE[(sx, sy)] = rings
return rings
def shadow_mask(sx, sy, w, h):
"""Flat per-cell multiplier on the flood level: the symbol's shadow.
Precomputed and flat so the inner loop pays one list index and one multiply
per cell, with no set membership test and no branch.
"""
mask = [1.0] * (w * h)
for ring, level in zip(_rim_cells(sx, sy), RIM_SHADOW):
for x, y in ring:
if 0 <= x < w and 0 <= y < h:
mask[y * w + x] = level
return mask
def draw_verse(scr, text):
"""Verse inside the flooded panel, on its own plate so it stays readable.
Text alone would fight the shockwave running underneath it, so the strip
is backed with the ramp's trough color — the same purple, at rest.
"""
row = scr.h - 2
if row < 0:
return
if len(text) > scr.w - 6:
text = text[: scr.w - 7] + "…"
plate = " " + text + " "
col = max(0, (scr.w - len(plate)) // 2)
# aurora runs without ricefx; fall back to Rosé Pine text-on-overlay.
style = (fg(ricefx.accent("text")) + bg_code(ricefx.ramp(0.68))
if ricefx is not None
else fg((224, 222, 244)) + bg_code(OVERLAY))
for k, ch in enumerate(plate):
scr.put(col + k, row, ch, style)
def draw_rain(scr, drops, phase):
chars = "░▒▓│╎|"
for d in drops:
d["y"] += d["spd"]
if d["y"] - d["ln"] > scr.h:
d["y"] = -float(d["ln"])
d["hue"] = (d["hue"] + 0.37) % 1.0
for k in range(d["ln"]):
yy = int(d["y"]) - k
v = max(0.15, 1.0 - k / d["ln"])
ch = chars[(k + int(d["y"])) % len(chars)]
scr.put(d["x"], yy, ch, fg(scale(pal(d["hue"] + phase), v)))
# ── aurora: northern-lights arc in the full poster rainbow ───────────────────
# The default splash. A wavy arc of light hangs in the upper third of a dark,
# star-filled sky; rays of varying length reach down from it and fade into
# the dark, while the poster palette (teal → gold → rose → love → iris)
# slides through the band. Most of the screen stays night sky — the aurora
# is a subject on it, not a fill.
#
# Unlike burst there is NOTHING to keep track of: no wavefront, no particle
# lists, no state machine — every cell is a pure function of (x, y, elapsed),
# built from smooth periodic terms. A renderer with no state has no state to
# corrupt, and every frame is valid regardless of frame rate or timing. It
# also needs no ricefx: the poster PALETTE is enough.
#
# Rendering rule (learned from the burst, see the note in draw_burst): GLYPH
# DENSITY and BRIGHTNESS are separate axes. Inside the band the fill is solid
# blocks with brightness carried by COLOR; the ░▒▓ ladder appears only where
# a ray is genuinely fading out, so the light reads as light, not as dither.
AUR_FADE_IN = 0.9 # seconds for the lights to breathe in from nothing
AUR_TOP = 0.14 # mean top edge of the arc, as a fraction of height
AUR_DRIFT = 0.045 # laps/sec the rainbow slides sideways through the arc
AUR_SPAN = 1.25 # rainbow laps across the terminal width
AUR_TILT = 0.07 # laps of hue shift from a ray's crest to its tip
AUR_CREST = 0.12 # fraction of a ray's length spent rising to full
AUR_STAR_CELLS = 55 # one star per this many screen cells
# Finer grids than the burst uses: the hue here runs along a straight axis,
# so at burst's 24 steps the seams line up into visible vertical stripes.
# The drift is slow (a cell crosses a 64-step boundary ~3×/sec), so the
# frame diff still skips almost everything.
AUR_POS_STEPS = 64 # distinct hues around one palette lap
AUR_V_STEPS = 20 # distinct brightness levels
# (spatial frequency, sway speed rad/s, amplitude as fraction of height) for
# the sine harmonics shaping the arc's top edge. Incommensurate frequencies
# and opposing speeds keep the sum from ever visibly repeating.
AUR_EDGE = ((0.043, 0.42, 0.050), (0.017, -0.27, 0.032), (0.089, 0.66, 0.020))
_AUR_CELL_CACHE = {}
def _aur_cell(posq, vq):
"""Cached (glyph, style) for one aurora cell — same quantization idea as
the burst flood: snap hue and brightness to a grid so the escapes come
from a dict and the frame diff can skip unchanged cells. Solid block down
to ~30% brightness, then the density ladder blends the ray tips and
feathered edges out into the dark."""
key = (posq, vq)
cell = _AUR_CELL_CACHE.get(key)
if cell is None:
vv = vq / AUR_V_STEPS
g = ("█" if vv >= 0.30 else "▓" if vv >= 0.18 else
"▒" if vv >= 0.10 else "░" if vv >= 0.045 else "·")
cell = (g, fg(scale(pal(posq / AUR_POS_STEPS), 0.08 + 0.92 * vv)))
_AUR_CELL_CACHE[key] = cell
return cell
class Aurora:
"""Per-launch aurora state: scratch columns and the fixed star field.
The stars are the only 'state', and they are immutable after __init__ —
fixed positions, fixed twinkle phases. Everything that moves each frame
is recomputed from elapsed time alone.
"""
def __init__(self, w, h, shadow=None):
self.w, self.h = w, h
self.shadow = shadow if shadow is not None else [1.0] * (w * h)
# Per-column scratch, refilled each frame: top edge, ray length, ray
# brightness, hue. Columns are cheap (w sin calls); cells are not.
self.E = [0.0] * w
self.L = [1.0] * w
self.B = [0.0] * w
self.POS = [0.0] * w
self.huestep = AUR_SPAN / max(1, w)
# Stars over the WHOLE sky — the arc and the symbol simply cover the
# ones behind them: (x, y, twinkle phase, hue 0..1).
self.stars = [(random.randrange(w), random.randrange(h),
random.uniform(0, math.tau), random.random())
for _ in range(max(12, (w * h) // AUR_STAR_CELLS))]
def draw_aurora(scr, aur, elapsed):
"""Draw sky + arc into the panel. Called before the symbol is drawn."""
W, H = scr.w, scr.h
t = elapsed
breathe = min(1.0, t / AUR_FADE_IN)
breathe *= breathe * (3.0 - 2.0 * breathe) # smoothstep, no hard pop
sin = math.sin
# Stars first, across the whole sky — rays draped over them just cover
# them, and uncover them again as they retract.
for x, y, ph, hue in aur.stars:
tw = 0.5 + 0.5 * sin(t * 1.6 + ph)
v = (0.14 + 0.50 * tw * tw) * breathe
scr.put(x, y, "✦" if v > 0.50 else "·", fg(scale(pal(hue), v)))
E, L, B, POS = aur.E, aur.L, aur.B, aur.POS
huestep, drift = aur.huestep, t * AUR_DRIFT
# Column pass: edge, ray length, ray brightness, hue. ~W sin calls a
# frame — noise next to the cell pass below.
for x in range(W):
e = AUR_TOP
for f, spd, amp in AUR_EDGE:
e += amp * sin(x * f + t * spd)
E[x] = e * H
# Ray length: two slow envelopes beating against each other pick out
# long streamers, a fast low-amplitude term makes the tips shimmer.
stretch = (0.5 + 0.5 * sin(x * 0.045 + t * 0.50)) \
* (0.5 + 0.5 * sin(x * 0.021 - t * 0.31))
L[x] = max(3.0, (0.16 + 0.38 * stretch
+ 0.04 * sin(x * 0.23 + t * 2.1)) * H)
# Ray brightness: a wave travelling along the arc × a slow swell,
# so light visibly runs through the band like the real thing — then a
# fine, slow striation (~9-cell period) so the band shows individual
# vertical rays instead of reading as one blob. Kept shallow: deep
# striping would tear the arc into disconnected stripes.
B[x] = (0.60 + 0.40 * sin(x * 0.13 - t * 1.5)) \
* (0.75 + 0.25 * sin(x * 0.047 + t * 0.85)) \
* (0.82 + 0.18 * sin(x * 0.71 - t * 0.55))
POS[x] = x * huestep + drift
shadow = aur.shadow
cache = _AUR_CELL_CACHE
cell_for = _aur_cell
cells = scr.cells
crest, tilt = AUR_CREST, AUR_TILT
pstep, vstep = AUR_POS_STEPS, AUR_V_STEPS
fall = 1.0 - crest
for y in range(H):
row = cells[y]
base = y * W
for x in range(W):
rel = y - E[x]
if rel < 0.0:
continue # sky above the arc
q = rel / L[x] # 0 at the crest, 1 at the tip
if q >= 1.0:
continue # sky below this ray's reach
# Profile down the ray: quick rise to a bright crest just under
# the top edge, then a long fade to nothing at the tip.
p = q / crest if q < crest else ((1.0 - q) / fall) ** 1.4
v = B[x] * p * breathe * shadow[base + x]
if v < 0.02:
continue
posq = int((POS[x] + q * tilt) * pstep) % pstep
vq = int(v * vstep)
cell = cache.get((posq, vq))
if cell is None:
cell = cell_for(posq, vq)
row[x] = cell
# ── rose: a Rose Pine rose window blooming around the symbol ─────────────────
# The default splash. A cathedral rose window unfolds outward from a gilded
# heart: concentric rings of petals — Fibonacci counts, alternate rings
# counter-rotating, seams offset by the golden angle so they never line up
# into spokes — with a slow wave of light forever running outward through
# them. The symbol sits in front at the window's heart, and loose petals
# drift down the star-filled sky around it.
#
# Stateless like aurora: given the fixed star/petal seeds from __init__,
# every cell is a pure function of (cell, time) — no wavefronts, no particle
# aging, nothing to corrupt — and it needs no ricefx. Same rendering rule as
# the other full-screen modes: glyph DENSITY and BRIGHTNESS are separate
# axes, so the window is solid blocks carried by color and the ░▒▓ ladder
# appears only where light is genuinely fading out.
ROSE_BLOOM_SECS = 2.0 # seconds for the window to bloom fully open
ROSE_RING = 4.8 # radial cells per petal ring (aspect-corrected)
ROSE_PETALS = (5, 8, 13, 21, 34, 55, 89) # petals per ring, inside out
ROSE_ROT = 0.09 # rad/s each ring turns; alternate rings counter-turn
ROSE_GOLDEN = 2.39996 # golden angle between rings' petal seams
ROSE_HEART = 2.0 # radius of the solid gilded heart, in cells
ROSE_EDGE = 2.5 # cells of feather at the bloom's rim
ROSE_MARGIN = 0.92 # bloom radius as a fraction of the shorter half-axis
ROSE_STAR_CELLS = 70 # one star per this many screen cells
ROSE_FALL_CELLS = 260 # one drifting petal per this many screen cells
ROSE_U_STEPS = 24 # quantized radial-color positions (cache key)
ROSE_V_STEPS = 14 # quantized brightness levels
# Every stop a literal Rose Pine accent (same law as the burst ramp): the
# window reads heart to rim as gold -> love -> rose -> love -> iris.
ROSE_BLOOM_STOPS = (
(246, 193, 119), # gold — the gilded heart
(235, 111, 146), # love
(235, 188, 186), # rose
(235, 111, 146), # love
(196, 167, 231), # iris — the rim
)
# Falling-petal tints (rose and love, dimmed via scale()).
ROSE_PETAL_TINTS = ((235, 188, 186), (235, 111, 146))
_ROSE_CELL_CACHE = {}
def use_rose_stops():
"""Symbol palette for rose mode: gold -> text -> foam -> subtle, cyclic.
Warm gilding and near-white keep the symbol the brightest thing at the
heart of the pink window; no pink stops, so it never melts into the
petals behind it."""
global STOPS
STOPS = [(246, 193, 119), (224, 222, 244),
(156, 207, 216), (144, 140, 170)]
def _rose_grad(u):
"""Clamped interpolation across ROSE_BLOOM_STOPS (heart u=0, rim u=1)."""
u = max(0.0, min(1.0, u))
x = u * (len(ROSE_BLOOM_STOPS) - 1)
i = int(x)
f = x - i
a = ROSE_BLOOM_STOPS[i]
b = ROSE_BLOOM_STOPS[min(i + 1, len(ROSE_BLOOM_STOPS) - 1)]
return tuple(int(a[k] + (b[k] - a[k]) * f) for k in range(3))
def _rose_cell(uq, vq):
"""Cached (glyph, style) for one window cell — same quantization idea as
the burst flood and aurora: snap color position and brightness to a grid
so the escapes come from a dict and the frame diff can skip cells."""
key = (uq, vq)
cell = _ROSE_CELL_CACHE.get(key)
if cell is None:
vv = vq / ROSE_V_STEPS
g = ("█" if vv >= 0.30 else "▓" if vv >= 0.18 else
"▒" if vv >= 0.10 else "░" if vv >= 0.045 else "·")
cell = (g, fg(scale(_rose_grad(uq / ROSE_U_STEPS), 0.08 + 0.92 * vv)))
_ROSE_CELL_CACHE[key] = cell
return cell
class Rose:
"""Per-launch rose-window state: cell geometry and the fixed seeds.
Like Burst, the geometry is STATIC — the window's centre never moves —
so radius and angle are computed once here, not once per cell per frame.
The stars and drifting petals are seeded once and immutable; their
motion is recomputed from elapsed time alone.
"""
def __init__(self, ccx, ccy, w, h, shadow=None):
self.w, self.h = w, h
self.shadow = shadow if shadow is not None else [1.0] * (w * h)
self.rmax = ROSE_MARGIN * min(w * ASPECT, h) / 2.0
n = w * h
self.D = [0.0] * n # radius, in halved-x space
self.A = [0.0] * n # angle
atan2, sqrt = math.atan2, math.sqrt
i = 0
for y in range(h):
dy = y - ccy
for x in range(w):
dx = (x - ccx) * ASPECT
self.D[i] = sqrt(dx * dx + dy * dy)
self.A[i] = atan2(dy, dx)
i += 1
# (x, y, twinkle phase, hue 0..1) — the window simply covers the
# stars behind it, like the aurora's arc does.
self.stars = [(random.randrange(w), random.randrange(h),
random.uniform(0, math.tau), random.random())
for _ in range(max(10, n // ROSE_STAR_CELLS))]
# (column, y offset, fall speed cells/s, sway amp, phase, tint index)
self.petals = [(random.randrange(w), random.uniform(0, h),
random.uniform(1.6, 3.8), random.uniform(1.5, 4.0),
random.uniform(0, math.tau), k & 1)
for k in range(max(5, n // ROSE_FALL_CELLS))]
def draw_rose(scr, rose, elapsed):
"""Draw sky + blooming window into the panel, before the symbol."""
W, H = scr.w, scr.h
t = elapsed
sin = math.sin
# Ease-out bloom: fast unfurl, gentle settle at full spread.
k = min(1.0, t / ROSE_BLOOM_SECS)
R = rose.rmax * (1.0 - (1.0 - k) ** 3)
# Stars first, across the whole sky.
for x, y, ph, hue in rose.stars:
tw = 0.5 + 0.5 * sin(t * 1.4 + ph)
v = 0.12 + 0.45 * tw * tw
scr.put(x, y, "✦" if v > 0.45 else "·", fg(scale(pal(hue), v)))
D, A = rose.D, rose.A
shadow = rose.shadow
cells = scr.cells
cache = _ROSE_CELL_CACHE
cell_for = _rose_cell
ring_len, rmax, edge, heart = ROSE_RING, rose.rmax, ROSE_EDGE, ROSE_HEART
ustep, vstep = ROSE_U_STEPS, ROSE_V_STEPS
nring = len(ROSE_PETALS)
# Per-ring rotation, once per frame: golden-angle offset + slow
# counter-rotation on alternate rings.
rots = [ROSE_GOLDEN * r + ROSE_ROT * t * (1 if r & 1 else -1)
for r in range(nring)]
for y in range(H):
row = cells[y]
base = y * W
for x in range(W):
i = base + x
d = D[i]
fade = (R - d) / edge # feather at the bloom's rim
if fade <= 0.0:
continue
if fade > 1.0:
fade = 1.0
if d < heart:
pang, frac = 1.0, 1.0 # the gilded heart, always lit
else:
rn = d / ring_len
ring = int(rn)
if ring >= nring:
ring = nring - 1
frac = rn - ring
pang = sin(ROSE_PETALS[ring] * (A[i] - rots[ring]) * 0.5)
if pang < 0.0:
pang = -pang
if pang < 0.08:
continue # the dark seam between petals
# Petal rim bright, base dark — rings read as overlapping petal
# layers — while a slow wave of light runs outward through the
# whole window.
v = (pang ** 0.7) * (0.30 + 0.70 * frac * frac) \
* (0.82 + 0.18 * sin(d * 0.45 - t * 1.7)) \
* fade * shadow[i]
if v < 0.045:
continue
uq = int(d / rmax * ustep)
if uq >= ustep:
uq = ustep - 1
cell = cache.get((uq, int(v * vstep)))
if cell is None:
cell = cell_for(uq, int(v * vstep))
row[x] = cell
# Loose petals drifting down in front, swaying as they fall.
for x0, y0, spd, amp, ph, tint in rose.petals:
yy = int((y0 + t * spd) % (H + 6.0) - 3.0)
xx = int(x0 + amp * sin(t * 0.9 + ph)) % W
v = 0.42 + 0.24 * sin(t * 2.3 + ph)
scr.put(xx, yy, "❀" if v > 0.55 else "✿",
fg(scale(ROSE_PETAL_TINTS[tint], v)))
# ── system specs (captured once from fastfetch) ──────────────────────────────
def capture_info():
"""System specs from fastfetch — piped in if the shell ran it, else ours.
Prefer the pipe. fastfetch identifies the Shell and Terminal modules by
walking UP the process tree, so whatever launched it is what it reports:
run as our subprocess it says "Shell: crossfetch, Terminal: Python 3.14".
The shell running `fastfetch ... | crossfetch --fetch` keeps zsh and kitty
as the parents, and the pipe is just how the answer gets here.
"""
lines = []
try:
piped = not sys.stdin.isatty()
except (AttributeError, ValueError, OSError):
piped = False
if piped:
try:
lines = sys.stdin.read().splitlines()
except (OSError, UnicodeDecodeError):
lines = []
if not lines and shutil.which("fastfetch") is not None:
try:
r = subprocess.run(
["fastfetch", "--logo", "none", "--pipe", "false"],
capture_output=True, text=True, timeout=6,
)
lines = r.stdout.splitlines()
except (OSError, subprocess.SubprocessError):
lines = []
while lines and not lines[-1].strip():
lines.pop()
return lines
def daily_verse():
"""Today's verse from ~/.config/crossfetch/verses.txt (rotates by date)."""
import datetime
f = _active_feast()
if f:
return f.verse
path = os.path.expanduser("~/.config/crossfetch/verses.txt")
try:
with open(path, encoding="utf-8") as f:
lines = [l.strip() for l in f if l.strip()]
except OSError:
return None
if not lines:
return None
doy = datetime.date.today().timetuple().tm_yday
return lines[doy % len(lines)]
# ── keypress (non-blocking) ──────────────────────────────────────────────────
def _raw_tty():
"""(fd, saved_attrs) for a non-blocking read of the controlling terminal.
Opened on /dev/tty rather than stdin so it still works when the splash is
started from a shell whose stdin is busy. (None, None) when the platform
or the environment cannot provide one; every caller degrades to
timeout-only exit.
"""
if termios is None:
return None, None
try:
fd = os.open("/dev/tty", os.O_RDONLY | os.O_NONBLOCK)
except OSError:
return None, None
try:
old = termios.tcgetattr(fd)
_ttymod.setcbreak(fd)
return fd, old
except (OSError, termios.error):
try:
os.close(fd)
except OSError:
pass
return None, None
def _restore_tty(fd, old):
if fd is None:
return
if old is not None:
try:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
except (OSError, termios.error):
pass
try:
os.close(fd)
except OSError:
pass
def _fps():
"""$CROSS_FPS, the frame-rate ceiling for the live dashboard."""
try:
return float(os.environ.get("CROSS_FPS", "60") or 60)
except ValueError:
return 60.0
def key_pressed(tty, wait):
# Floored: callers pass whatever is left of a frame budget, which is 0 on
# a frame that overran. Yielding nothing at all would spin a core for the
# whole splash without drawing anything extra.
wait = max(0.002, wait)
if tty is None:
time.sleep(wait)
return False
r, _, _ = select.select([tty], [], [], wait)
if r:
try:
os.read(tty, 64) # drain so the key doesn't leak to the shell
except OSError:
pass
return True
return False
# ── main live view ───────────────────────────────────────────────────────────
def run(mode, timeout):
"""Run the live splash. Returns True if it actually entered the render
loop (drew to the alt screen), False on every early bail (not a tty,
NO_COLOR, terminal-size lookup failed, or terminal too small) — callers
that only want to know "did something get drawn" can check this instead
of assuming a call always renders."""
if not sys.stdout.isatty() or os.environ.get("NO_COLOR"):
return False
try:
cols, rows = os.get_terminal_size()
except OSError:
return False
sw = SW # symbol width in columns
if rows < CH + 2 or cols < sw + 6:
return False # too small to render cleanly — skip
if mode == "burst" and ricefx is None:
mode = "ring" # no palette lib, no flood
if mode == "burst":
use_burst_palette() # also swaps STOPS
elif mode == "rose":
use_rose_stops() # gilded symbol, no pinks
# Splash = symbol + effect + verse only, centered. No system info (fastfetch
# shows that statically after the splash), which also keeps startup fast.
if mode in ("burst", "aurora", "rose"):
# These own the WHOLE terminal — that is the point of them. The verse
# is drawn inside the panel instead of below it, since there is no
# below.
screen_h, reserve = rows, 0
else:
content_h = CH + 6 # symbol + room for the ring
reserve = 2 if rows >= content_h + 2 else 0 # row for the verse footer
screen_h = min(rows - reserve, content_h)
sx = (cols - sw) // 2
sy = (screen_h - CH) // 2
ccx, ccy = sx + sw / 2.0, sy + CH / 2.0
rx, ry = sw / 2.0 + 5, CH / 2.0 + 2
scr = Panel(cols, screen_h)
burst = Burst(ccx, ccy, cols, screen_h,
shadow_mask(sx, sy, cols, screen_h)) if mode == "burst" else None
aurora = Aurora(cols, screen_h,
shadow_mask(sx, sy, cols, screen_h)) if mode == "aurora" else None
rosewin = Rose(ccx, ccy, cols, screen_h,
shadow_mask(sx, sy, cols, screen_h)) if mode == "rose" else None
drops = [{"x": random.randint(0, cols - 1),
"y": random.uniform(-screen_h, 0),
"spd": random.uniform(0.5, 1.4),
"ln": random.randint(3, 8),
"hue": random.random()} for _ in range(max(8, cols // 3))]
# raw, non-blocking tty for "press any key to exit"
tty_fd, old = _raw_tty()
try:
# alt screen + hidden cursor only inside the try, so the finally
# below always restores them even if Ctrl-C lands immediately
sys.stdout.write(ALT + HIDE)
# daily verse, dim + centered, in the reserved footer row
if reserve:
v = daily_verse()
if v:
if len(v) > cols - 4:
v = v[: cols - 5] + "…"
vcol = max(1, (cols - len(v)) // 2)
sys.stdout.write(at(screen_h + 2, vcol) + fg((144, 140, 170)) + v + RESET)
sys.stdout.flush()
verse_line = daily_verse() if mode in ("burst", "aurora", "rose") else None
# Pace on a wall-clock budget rather than sleeping a fixed slice after
# every frame. A fixed 0.04s sleep ADDS to the render time, so a frame
# that took 25ms to draw landed 65ms apart — ~15fps, and the jitter
# between a cheap early frame and an expensive full-screen one is what
# made the motion read as stuttery rather than merely slow.
budget = 1.0 / max(15.0, min(120.0, _fps()))
start = time.time()
while True:
frame_start = time.time()
elapsed = frame_start - start
phase = elapsed * 0.6
reveal = min(1.0, elapsed / REVEAL_SECS) # one-shot purple ripple
cur = ("rain" if elapsed < 1.6 else "ring") if mode == "both" else mode
scr.clear()
if cur == "burst":
draw_burst(scr, burst, elapsed)
reveal = 1.0 # the symbol is the fuse, not the payload
elif cur == "aurora":
# reveal stays live: the purple ripple surfaces the symbol
# while the lights are still breathing in behind it.
draw_aurora(scr, aurora, elapsed)
elif cur == "rose":
# reveal stays live here too: the symbol surfaces while the
# window is still blooming open around it.
draw_rose(scr, rosewin, elapsed)
elif cur == "rain":
draw_rain(scr, drops, phase)
else:
draw_ring(scr, ccx, ccy, rx, ry, elapsed, phase)
draw_symbol(scr, sx, sy, phase, reveal)
if verse_line:
draw_verse(scr, verse_line)
scr.flush()
if timeout and time.time() - start >= timeout:
break
# Whatever is left of this frame's budget doubles as the keypress
# poll, so a slow frame still checks for input — just without
# waiting on top of the time it already spent.
if key_pressed(tty_fd, max(0.0, budget - (time.time() - frame_start))):
break
except KeyboardInterrupt:
pass
finally:
sys.stdout.write(SHOW + UNALT)
sys.stdout.flush()
_restore_tty(tty_fd, old)
return True
def main():
args = sys.argv[1:]
if args and args[0] in ("-h", "--help"):
print(__doc__.strip())
return
set_symbol(os.environ.get("CROSS_SYMBOL"))
f = _active_feast()
if f:
set_symbol(f.emblem) # feast emblem overrides the daily rotation
if args and args[0] == "--sync-fastfetch":
sys.exit(sync_fastfetch())
if args and args[0] == "--logo":
if len(args) > 1: # crossfetch --logo [chi|orthodox]
set_symbol(args[1])
use_season_stops()
print_logo()
return
if args and args[0] == "--fetch":
try:
secs = float(args[1]) if len(args) > 1 \
else float(os.environ.get("CROSS_GLOW", "1.6") or 0)
except ValueError:
secs = 1.6
use_season_stops()
fetch(secs)
return
if args and args[0] == "--feast":
if liturgy is None:
print("crossfetch: liturgy module missing", file=sys.stderr)
sys.exit(2)
fid = args[1] if len(args) > 1 else (f.id if f else "easter_day")
fd = liturgy.FEAST_DEFS.get(fid)
if fd is None:
print(f"unknown feast {fid!r}; available: "
f"{', '.join(sorted(liturgy.FEAST_DEFS))}", file=sys.stderr)
sys.exit(2)
global FORCED_FEAST
FORCED_FEAST = fd
set_symbol(fd.emblem)
try:
timeout = float(os.environ.get("CROSS_TIMEOUT", "0") or 0)
except ValueError:
timeout = 0.0
run("burst", timeout)
return
modes = ("rose", "aurora", "burst", "rain", "ring", "both")
mode = args[0] if args and args[0] in modes \
else os.environ.get("CROSS_MODE", "rose")
if mode not in modes:
mode = "rose"
try:
timeout = float(os.environ.get("CROSS_TIMEOUT", "0") or 0)
except ValueError:
timeout = 0.0
if f and _feast_unseen(f) and sys.stdout.isatty():
# Feast day: fullscreen burst in the feast's colors, once per year
# (like hyfetch's pride-month animation). Keypress still skips. Only
# mark it seen if it actually rendered — an early bail inside run()
# (NO_COLOR, tiny terminal, ...) must not burn the one-shot.
if run("burst", timeout if timeout else 8.0):
_mark_feast_seen(f)
return
run(mode, timeout)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
if sys.stderr.isatty():
sys.stderr.write(SHOW) # never leave the cursor hidden
sys.stderr.write("\n")
sys.exit(130)
except BrokenPipeError:
# e.g. `crossfetch --logo | head` — exit quietly, no traceback
try:
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
except OSError:
pass
sys.exit(0)