#!/usr/bin/env python3 """ricefx — the shared purple-shimmer effect library for the local tools. One wave, one ramp, one palette. Every custom tool in ~/.local/bin imports this instead of hand-rolling its own Rose Pine tuples (there were six copies before this file existed). The effect A purple wave sweeping across a span of cells. Cell i takes its color from ramp((i / WAVELEN) - t * SPEED), so the crest walks along as t advances. Banners sweep, progress bars ripple, spinners pulse and crossfetch's burst floods the screen — all of them are that one expression. The ramp Rose Pine purples only, anchored on iris #c4a7e7, several shades deep so the wave has a crest, a body and a trough instead of reading as one flat color. It is CYCLIC: index 0 follows the last stop with no seam, so a wave can run forever without a visible restart. On a LIGHT background the crest is the DEEPEST purple, not the brightest — contrast against cream runs the opposite direction from contrast against charcoal. `theme()` picks the right ramp; nothing else has to care. Usage (python tools): import ricefx print(ricefx.sweep("MORSE", t)) # one line, shimmered print(ricefx.bar(0.62, 24, t)) # shimmering progress bar ricefx.banner_sweep(BANNER_LINES) # one-shot animated reveal Usage (shell tools): source "$(dirname "$0")/ricefx.sh" Usage (CLI): ricefx.py demo every effect on one screen ricefx.py sweep TEXT animate one line ricefx.py bar [PCT] animate a bar ricefx.py ramp dump the ramp as swatches Env: RICEFX_THEME dawn | dark force a ramp (default: detect) RICEFX_OFF any value disable every effect (static fallback) NO_COLOR any value same, honoured everywhere """ from __future__ import annotations import math import os import re import sys import time __all__ = [ "theme", "ramp", "shimmer", "sink", "fg", "bg", "RESET", "enabled", "sweep", "bar", "spin", "banner_sweep", "visible_len", "BACKGROUND", "WAVELEN", "SPEED", ] # ── ramps ─────────────────────────────────────────────────────────────────── # Ordered crest → trough → back up, and read CYCLICALLY. The flat run of two # identical overlay stops is deliberate: it is the gap between waves, without # which the screen reads as a solid pulsing block rather than bands. RAMPS = { # Rose Pine Dawn. Cream background, so the crest is the DEEPEST purple. "dawn": [ (111, 92, 134), # deep iris — crest (144, 122, 169), # iris (dawn) (196, 167, 231), # iris — #c4a7e7 (203, 184, 221), # pale lilac (224, 214, 229), # faint (242, 233, 225), # overlay — trough (242, 233, 225), # overlay — trough held: the gap between waves (214, 197, 231), # rise back into the next crest ], # Rose Pine base dark (not Moon). The crest is the BRIGHTEST. "dark": [ (232, 213, 255), # spark — crest (196, 167, 231), # iris — #c4a7e7 (144, 140, 170), # subtle — #908caa (82, 79, 103), # highlight high (64, 61, 82), # highlight med (38, 35, 58), # overlay — trough (38, 35, 58), # overlay — trough held (110, 106, 134), # rise back ], } # The SOLID ramps never reach the background. RAMPS has a trough that sinks all # the way to overlay, which is right for a wave crossing empty space (banners, # bars) — but wrong for filling a surface, where it would punch cream holes in # the middle of the fill. Symmetric, so they still wrap seamlessly. RAMPS_SOLID = { "dawn": [ (111, 92, 134), # deep iris — crest (144, 122, 169), # iris (dawn) (196, 167, 231), # iris — #c4a7e7 (214, 197, 231), (228, 215, 238), # lightest — still plainly purple, never cream (214, 197, 231), (196, 167, 231), (144, 122, 169), ], "dark": [ (232, 213, 255), # spark — crest (196, 167, 231), # iris — #c4a7e7 (144, 140, 170), (110, 106, 134), (82, 79, 103), # darkest — still plainly purple, never base (110, 106, 134), (144, 140, 170), (196, 167, 231), ], } BACKGROUNDS = {"dawn": (250, 244, 237), "dark": (25, 23, 36)} # Minimum luminance separation from the background a TEXT cell may have. The # solid ramp still runs pale enough at its light end to vanish under a glyph on # cream — fine for filling a surface, unreadable for letters. TEXT_MIN_DELTA = 0.26 def _lum(c) -> float: return (0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]) / 255.0 def _legible(col, bgc, crest): """Pull a color toward the crest until it separates from the background. Derived rather than hand-tabulated, so editing RAMPS_SOLID cannot silently produce a text ramp that fails on one of the two themes. """ lc, lb, lk = _lum(col), _lum(bgc), _lum(crest) if abs(lb - lc) >= TEXT_MIN_DELTA: return col target = lb - TEXT_MIN_DELTA if lk < lb else lb + TEXT_MIN_DELTA if abs(lk - lc) < 1e-6: return crest t = (lc - target) / (lc - lk) t = 0.0 if t < 0.0 else (1.0 if t > 1.0 else t) return (int(col[0] + (crest[0] - col[0]) * t), int(col[1] + (crest[1] - col[1]) * t), int(col[2] + (crest[2] - col[2]) * t)) # Accent set kept beside the ramp so tools can drop their private copies. ACCENTS = { "dawn": {"base": (250, 244, 237), "surface": (255, 250, 243), "overlay": (242, 233, 225), "muted": (152, 147, 165), "subtle": (121, 117, 147), "text": (87, 82, 121), "love": (180, 99, 122), "gold": (234, 157, 52), "rose": (215, 130, 126), "pine": (40, 105, 131), "foam": (86, 148, 159), "iris": (144, 122, 169), "highlightLow": (244, 237, 232), "highlightMed": (223, 218, 217), "highlightHigh": (206, 202, 205)}, "dark": {"base": (25, 23, 36), "surface": (31, 29, 46), "overlay": (38, 35, 58), "muted": (110, 106, 134), "subtle": (144, 140, 170), "text": (224, 222, 244), "love": (235, 111, 146), "gold": (246, 193, 119), "rose": (235, 188, 186), "pine": (49, 116, 143), "foam": (156, 207, 216), "iris": (196, 167, 231), "highlightLow": (33, 32, 46), "highlightMed": (64, 61, 82), "highlightHigh": (82, 79, 103)}, # Tokyo Night (night variant): https://github.com/folke/tokyonight.nvim "tokyo-night": {"base": (26, 27, 38), "surface": (31, 35, 53), "overlay": (41, 46, 66), "muted": (86, 95, 137), "subtle": (169, 177, 214), "text": (192, 202, 245), "love": (247, 118, 142), "gold": (224, 175, 104), "rose": (255, 158, 100), "pine": (122, 162, 247), "foam": (125, 207, 255), "iris": (187, 154, 247), "highlightLow": (41, 46, 66), "highlightMed": (65, 72, 104), "highlightHigh": (84, 92, 126)}, # Gruvbox dark (medium): https://github.com/morhetz/gruvbox "gruvbox": {"base": (40, 40, 40), "surface": (60, 56, 54), "overlay": (80, 73, 69), "muted": (146, 131, 116), "subtle": (189, 174, 147), "text": (235, 219, 178), "love": (251, 73, 52), "gold": (250, 189, 47), "rose": (254, 128, 25), "pine": (131, 165, 152), "foam": (142, 192, 124), "iris": (211, 134, 155), "highlightLow": (60, 56, 54), "highlightMed": (80, 73, 69), "highlightHigh": (102, 92, 84)}, # Catppuccin Mocha: https://github.com/catppuccin/catppuccin "catppuccin-mocha": {"base": (30, 30, 46), "surface": (49, 50, 68), "overlay": (69, 71, 90), "muted": (108, 112, 134), "subtle": (166, 173, 200), "text": (205, 214, 244), "love": (243, 139, 168), "gold": (249, 226, 175), "rose": (250, 179, 135), "pine": (137, 180, 250), "foam": (148, 226, 213), "iris": (203, 166, 247), "highlightLow": (49, 50, 68), "highlightMed": (69, 71, 90), "highlightHigh": (88, 91, 112)}, # Nord: https://www.nordtheme.com "nord": {"base": (46, 52, 64), "surface": (59, 66, 82), "overlay": (67, 76, 94), "muted": (76, 86, 106), "subtle": (216, 222, 233), "text": (236, 239, 244), "love": (191, 97, 106), "gold": (235, 203, 139), "rose": (208, 135, 112), "pine": (94, 129, 172), "foam": (136, 192, 208), "iris": (180, 142, 173), "highlightLow": (59, 66, 82), "highlightMed": (67, 76, 94), "highlightHigh": (76, 86, 106)}, # Dracula: https://draculatheme.com (no true blue/teal accents — pine # borrows comment-blue, which doubles as muted; the contrast guard and # burst shoulders handle the overlap) "dracula": {"base": (40, 42, 54), "surface": (52, 55, 70), "overlay": (68, 71, 90), "muted": (98, 114, 164), "subtle": (189, 195, 225), "text": (248, 248, 242), "love": (255, 121, 198), "gold": (241, 250, 140), "rose": (255, 184, 108), "pine": (98, 114, 164), "foam": (139, 233, 253), "iris": (189, 147, 249), "highlightLow": (52, 55, 70), "highlightMed": (68, 71, 90), "highlightHigh": (98, 114, 164)}, } def _spark(acc): """Ramp crest: the theme's iris lifted toward text — same trick as the hand-tuned dark ramp's (232, 213, 255).""" return tuple(int(i + (t - i) * 0.4) for i, t in zip(acc["iris"], acc["text"])) # Derive wave/solid ramps + background for every theme that only defines # accents (the hand-tuned dawn/dark entries stay exactly as they are). for _name, _acc in ACCENTS.items(): if _name in RAMPS: continue RAMPS[_name] = [_spark(_acc), _acc["iris"], _acc["subtle"], _acc["highlightHigh"], _acc["highlightMed"], _acc["overlay"], _acc["overlay"], _acc["muted"]] RAMPS_SOLID[_name] = [_spark(_acc), _acc["iris"], _acc["subtle"], _acc["muted"], _acc["highlightHigh"], _acc["muted"], _acc["subtle"], _acc["iris"]] BACKGROUNDS[_name] = _acc["base"] RAMPS_TEXT = { name: [_legible(c, BACKGROUNDS[name], stops[0]) for c in stops] for name, stops in RAMPS_SOLID.items() } # NOTE on dimming: Rose Pine has no dark SATURATED tones — every dark member of # the palette (overlay, the highlights) is neutral. So fading an accent toward # the background does not give you "a darker gold", it gives you khaki, which # is not a Rose Pine colour at all. When something needs a dim accent, reach # for a real dark stop from the table above and let the accent stay at full # strength over a smaller area. sink() is for fading OUT, not for shading. WAVELEN = 14.0 # cells from one crest to the next SPEED = 1.35 # crests per second, drifting left→right _THEME: str | None = None def theme() -> str: """dawn | dark — explicit env first, then the terminal's own report. COLORFGBG is "fg;bg" and a bg of 7/15 means a light terminal; it is the same probe ytget already used, kept identical so the two never disagree. """ global _THEME if _THEME is not None: return _THEME choice = os.environ.get("RICEFX_THEME", "").strip().lower() choice = {"rose-pine": "dark", "rose-pine-dawn": "dawn"}.get(choice, choice) if choice in RAMPS: _THEME = choice return _THEME if choice: print(f"ricefx: unknown RICEFX_THEME {choice!r}, using dark " f"(known: {', '.join(sorted(RAMPS))})", file=sys.stderr) fgbg = os.environ.get("COLORFGBG", "") if ";" in fgbg: tail = fgbg.rsplit(";", 1)[-1] if tail.isdigit(): _THEME = "dawn" if int(tail) >= 7 else "dark" return _THEME _THEME = "dark" # the rice is base-dark Rosé Pine return _THEME def accent(name: str) -> tuple[int, int, int]: """A Rose Pine accent for the active theme — `accent("gold")` etc.""" return ACCENTS[theme()][name] BACKGROUND = None # resolved lazily so importing never reads the env def background() -> tuple[int, int, int]: return BACKGROUNDS[theme()] # ── color math ────────────────────────────────────────────────────────────── def ramp(t: float, solid: bool = False, kind: str | None = None): """Sample the purple ramp at cyclic position t (any float; 1.0 = one lap). kind picks which of the three ramps to read, each with one job: "wave" fades all the way to the background — a crest crossing empty space "solid" never reaches the background — filling a surface "text" never loses contrast with the background — glyphs solid=True is shorthand for kind="solid". """ kind = kind or ("solid" if solid else "wave") stops = {"wave": RAMPS, "solid": RAMPS_SOLID, "text": RAMPS_TEXT}[kind][theme()] n = len(stops) x = (t % 1.0) * n i = int(x) f = x - i a, b = stops[i % n], 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 shimmer(i: float, t: float, wavelen: float = WAVELEN, speed: float = SPEED, kind: str = "text"): """Color of cell i at time t — THE effect. Everything else wraps this. Defaults to the text ramp: nearly every caller is coloring glyphs, and a glyph that fades into the background is a bug, not a shimmer. """ return ramp(i / wavelen - t * speed, kind=kind) def sink(rgb, v: float): """Fade a color toward the terminal background (v=1 full, v=0 gone). Fading toward the BACKGROUND rather than toward black is what keeps the effect legible on a light terminal: multiplying toward black is the dark-terminal idiom and reads as *more* contrast on cream, not less. """ v = 0.0 if v < 0.0 else (1.0 if v > 1.0 else v) b = background() return (int(b[0] + (rgb[0] - b[0]) * v), int(b[1] + (rgb[1] - b[1]) * v), int(b[2] + (rgb[2] - b[2]) * v)) def mix(a, b, t: float): """Blend rgb a→b by t.""" t = 0.0 if t < 0.0 else (1.0 if t > 1.0 else t) return (int(a[0] + (b[0] - a[0]) * t), int(a[1] + (b[1] - a[1]) * t), int(a[2] + (b[2] - a[2]) * t)) def fg(rgb) -> str: return f"\x1b[38;2;{rgb[0]};{rgb[1]};{rgb[2]}m" def bg(rgb) -> str: return f"\x1b[48;2;{rgb[0]};{rgb[1]};{rgb[2]}m" RESET = "\x1b[0m" BOLD = "\x1b[1m" HIDE, SHOW = "\x1b[?25l", "\x1b[?25h" _ANSI = re.compile(r"\x1b\[[0-9;?]*[a-zA-Z]") def visible_len(s: str) -> int: return len(_ANSI.sub("", s)) # ── gating ────────────────────────────────────────────────────────────────── def enabled(stream=None) -> bool: """Effects run only on an interactive stream the user has not opted out of. Anything piped, redirected, or NO_COLOR'd gets the static fallback — a tool's data output must never carry escape bytes it did not ask for. """ if os.environ.get("NO_COLOR") is not None: return False if os.environ.get("RICEFX_OFF"): return False stream = stream or sys.stderr try: return bool(stream.isatty()) except (AttributeError, ValueError): return False # ── effects ───────────────────────────────────────────────────────────────── def sweep(text: str, t: float = 0.0, wavelen: float = WAVELEN, speed: float = SPEED, offset: float = 0.0) -> str: """Shimmer one line of text. Spaces stay uncolored so no escape runs are wasted on gaps — meaningful for block-letter banners, which are mostly gap.""" out, last = [], None for i, ch in enumerate(text): if ch == " ": if last is not None: out.append(RESET) last = None out.append(" ") continue code = fg(shimmer(i + offset, t, wavelen, speed)) if code != last: out.append(code) last = code out.append(ch) if last is not None: out.append(RESET) return "".join(out) RAMP_BLOCKS = "▁▂▃▄▅▆▇█" def bar(frac: float, width: int = 24, t: float = 0.0, wavelen: float = WAVELEN, speed: float = SPEED) -> str: """Progress bar whose filled span carries the wave. The wave is sampled in ABSOLUTE cell coordinates, not relative to the fill edge, so crests hold their place on screen while the bar grows past them — a bar phased off its own length looks like it is sliding backwards. """ frac = 0.0 if frac < 0.0 else (1.0 if frac > 1.0 else frac) filled = int(round(frac * width)) track = sink(ramp(0.0, kind="text"), 0.26) # the unfilled rail, recessive out = [] for i in range(width): if i < filled: c = shimmer(i, t, wavelen, speed) # Crest cells stand tallest, so the bar has relief, not just hue. h = (math.sin((i / wavelen - t * speed) * math.tau) + 1) / 2 out.append(fg(c) + RAMP_BLOCKS[int(h * (len(RAMP_BLOCKS) - 1))]) else: out.append(fg(track) + "▁") return "".join(out) + RESET SPIN_FRAMES = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏" def spin(t: float, fps: float = 12.0) -> str: """Braille spinner, colored by the wave so it pulses as it turns.""" ch = SPIN_FRAMES[int(t * fps) % len(SPIN_FRAMES)] return fg(shimmer(0, t)) + ch + RESET def banner_sweep(lines, stream=None, duration: float = 0.42, fps: float = 30.0, settle: bool = True) -> None: """One-shot shimmer pass over a block-letter banner, then settle. The crest starts off the left edge and exits past the right, so every cell is crossed exactly once — a banner that merely cycles in place reads as "still loading" instead of "arrived". Falls back to a single static gradient print when effects are disabled, so callers never need their own `if tty` branch. """ stream = stream or sys.stderr lines = list(lines) if not lines: return width = max(len(l) for l in lines) if not enabled(stream): for l in lines: stream.write(l + "\n") stream.flush() return span = width + 2 * WAVELEN # crest travels fully across and out frames = max(1, int(duration * fps)) up = f"\x1b[{len(lines)}A" stream.write(HIDE) try: for f in range(frames + 1): # offset shifts the wave; -WAVELEN starts it just off the left edge off = -WAVELEN + span * (f / frames) buf = [] for row, l in enumerate(lines): # rows lag slightly so the crest leans, rather than marching # as one rigid vertical bar down the whole banner buf.append(sweep(l, 0.0, offset=-off + row * 1.5) + "\x1b[K\n") stream.write("".join(buf)) stream.flush() if f != frames: time.sleep(duration / frames) stream.write(up) if settle: # settle: park the crest just past the right edge so the banner # keeps a gradient but no longer looks mid-animation stream.write(up) for row, l in enumerate(lines): stream.write(sweep(l, 0.0, offset=width * 0.35 + row * 1.5) + "\x1b[K\n") finally: stream.write(SHOW + RESET) stream.flush() def rule(width: int, t: float = 0.0, ch: str = "─") -> str: """A shimmering hairline — the divider idiom every tool already uses.""" return sweep(ch * width, t) # ── CLI: demo / preview ───────────────────────────────────────────────────── def _demo() -> None: art = [ "█▀█ █ █▀▀ █▀▀ █▀▀ ▀▄▀", "█▀▄ █ █▄▄ ██▄ █▀░ █░█", ] out = sys.stdout out.write(f"\n theme: {theme()} ramp anchored on iris #c4a7e7\n\n") banner_sweep([" " + l for l in art], stream=out) out.write("\n") start = time.time() try: while time.time() - start < 6.0: t = time.time() - start out.write("\x1b[s") out.write(f" bar {bar(min(1.0, t / 5.0), 34, t)}" f" {int(min(1.0, t / 5.0) * 100):3d}%\n") out.write(f" spin {spin(t)} working\n") out.write(f" rule {rule(34, t)}\n") out.write(f" text {sweep('the quick brown fox jumps', t)}\n") out.flush() time.sleep(1 / 30) out.write("\x1b[u") except KeyboardInterrupt: pass out.write("\x1b[4B\n") out.flush() def _ramp_dump() -> None: for name, stops in RAMPS.items(): sys.stdout.write(f" {name:5s} ") for s in stops: sys.stdout.write(bg(s) + " ") sys.stdout.write(RESET + "\n") sys.stdout.write("\n continuous:\n ") for i in range(64): sys.stdout.write(bg(ramp(i / 64)) + " ") sys.stdout.write(RESET + "\n") def _animate(render, secs: float = 5.0) -> None: start = time.time() sys.stdout.write(HIDE) try: while time.time() - start < secs: t = time.time() - start sys.stdout.write("\r\x1b[K" + render(t)) sys.stdout.flush() time.sleep(1 / 30) except KeyboardInterrupt: pass finally: sys.stdout.write(SHOW + RESET + "\n") TABLE_OPEN = "# >>> ricefx table >>>" TABLE_CLOSE = "# <<< ricefx table <<<" def _table_write(path: str) -> None: """Splice fresh tables between the markers in ricefx.sh, in place. Regenerating by rebuilding the whole file loses every hand edit made to the shell functions; only the marked region belongs to the generator. """ import io with open(path, encoding="utf-8") as f: text = f.read() if TABLE_OPEN not in text or TABLE_CLOSE not in text: sys.exit(f"ricefx: {path} has no table markers — refusing to rewrite it") head = text[: text.index(TABLE_OPEN)] tail = text[text.index(TABLE_CLOSE):] buf = io.StringIO() real, sys.stdout = sys.stdout, buf try: _table_sh() finally: sys.stdout = real with open(path, "w", encoding="utf-8") as f: f.write(head + buf.getvalue() + tail) print(f"ricefx: tables refreshed in {path}") def _table_sh() -> None: """Emit the ramp as shell arrays, so ricefx.sh needs no python per frame.""" steps = 48 print(f"{TABLE_OPEN} generated — do not hand-edit") print(f"RFX_STEPS={steps}") suffix = {"wave": "", "solid": "_SOLID", "text": "_TEXT"} for name in ("dawn", "dark"): for kind in ("wave", "solid", "text"): global _THEME _THEME = name var = f"RFX_{name.upper()}{suffix[kind]}" cols = " ".join( '"{}"'.format(";".join(str(v) for v in ramp(i / steps, kind=kind))) for i in range(steps)) print(f"{var}=({cols})") _THEME = None def main(argv) -> int: cmd = argv[0] if argv else "demo" if cmd in ("-h", "--help", "help"): print(__doc__.strip()) elif cmd == "demo": _demo() elif cmd == "ramp": _ramp_dump() elif cmd == "table": if len(argv) > 2 and argv[1] == "--write": _table_write(argv[2]) else: _table_sh() elif cmd == "banner": # `ricefx.py banner LINE...` — the shell tools' animated banner, run # here rather than reimplemented in sh so both look identical. banner_sweep(argv[1:], stream=sys.stdout) elif cmd == "sweepline": sys.stdout.write(sweep(" ".join(argv[1:]), 0.0) + "\n") elif cmd == "sweep": text = " ".join(argv[1:]) or "ricefx" _animate(lambda t: sweep(text, t)) elif cmd == "bar": try: pct = float(argv[1]) / 100.0 if len(argv) > 1 else None except ValueError: pct = None _animate(lambda t: bar(pct if pct is not None else min(1.0, t / 5), 34, t) + f" {int((pct if pct is not None else min(1.0, t / 5)) * 100):3d}%") else: sys.stderr.write(f"ricefx: unknown command {cmd!r}\n") return 2 return 0 if __name__ == "__main__": try: sys.exit(main(sys.argv[1:])) except KeyboardInterrupt: sys.stdout.write(SHOW + RESET + "\n") sys.exit(130) except BrokenPipeError: sys.exit(0)