mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-27 03:15:08 +00:00
feat(themes): load CLI themes from YAML files, with gradients
Ship 11 themes as YAML and read user themes from directories.themes, with extends, styles and gradients (banner, bar, pulse, rule, panel); env theme lists themes and plays an animated sample, and dl pins a moving banner.
This commit is contained in:
+44
-11
@@ -1,7 +1,9 @@
|
||||
import atexit
|
||||
import logging
|
||||
import signal
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
import click
|
||||
import urllib3
|
||||
@@ -12,19 +14,20 @@ from rich.text import Text
|
||||
from urllib3.exceptions import InsecureRequestWarning
|
||||
|
||||
from unshackle.core import __code_hash__, __version__
|
||||
from unshackle.core import console as console_module
|
||||
from unshackle.core.commands import Commands
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.console import ComfyRichHandler, console
|
||||
from unshackle.core.console import ComfyRichHandler, Gradient, PinnedLive, console
|
||||
from unshackle.core.constants import context_settings
|
||||
from unshackle.core.update_checker import UpdateChecker
|
||||
from unshackle.core.utilities import close_debug_logger, init_debug_logger
|
||||
|
||||
|
||||
def print_banner() -> None:
|
||||
"""Print the ASCII banner with the version line."""
|
||||
console.print(
|
||||
Padding(
|
||||
Group(
|
||||
def banner() -> Padding:
|
||||
"""The ASCII banner with the version line."""
|
||||
return Padding(
|
||||
Group(
|
||||
Gradient(
|
||||
Text(
|
||||
r"▄• ▄▌ ▐ ▄ .▄▄ · ▄ .▄ ▄▄▄· ▄▄· ▄ •▄ ▄▄▌ ▄▄▄ ." + "\n"
|
||||
r"█▪██▌•█▌▐█▐█ ▀. ██▪▐█▐█ ▀█ ▐█ ▌▪█▌▄▌▪██• ▀▄.▀·" + "\n"
|
||||
@@ -32,17 +35,39 @@ def print_banner() -> None:
|
||||
r"▐█▄█▌██▐█▌▐█▄▪▐███▌▐▀▐█ ▪▐▌▐███▌▐█.█▌▐█▌▐▌▐█▄▄▌" + "\n"
|
||||
r" ▀▀▀ ▀▀ █▪ ▀▀▀▀ ▀▀▀ · ▀ ▀ ·▀▀▀ ·▀ ▀.▀▀▀ ▀▀▀ ",
|
||||
style="ascii.art",
|
||||
justify="center",
|
||||
),
|
||||
"banner",
|
||||
"ascii.art",
|
||||
),
|
||||
Text.from_markup(
|
||||
f"v [repr.number]{__version__}[/]{f' ({__code_hash__})' if __code_hash__ else ''}"
|
||||
f" - © 2025-{datetime.now().year} github.com/unshackle-dl/unshackle",
|
||||
justify="center",
|
||||
),
|
||||
(1, 11, 1, 10),
|
||||
expand=True,
|
||||
),
|
||||
justify="center",
|
||||
(1, 11, 1, 10),
|
||||
expand=True,
|
||||
)
|
||||
|
||||
|
||||
def print_banner() -> None:
|
||||
"""Print the ASCII banner with the version line."""
|
||||
console.print(banner())
|
||||
|
||||
|
||||
def pins_banner(subcommand: Optional[str], args: list[str]) -> bool:
|
||||
"""Whether to pin the moving banner over this command's output: only dl, and not for its help.
|
||||
|
||||
It needs a theme with a banner gradient and a colour terminal. Help prints while Click parses the arguments,
|
||||
and the pinned area would wrap it again at its own width; usage errors print after the pinned area closes.
|
||||
"""
|
||||
if subcommand != "dl" or not console_module.theme_gradients.get("banner") or not PinnedLive.wanted(console):
|
||||
return False
|
||||
help_options: list[str] = context_settings["help_option_names"] # type: ignore[assignment]
|
||||
return not set(args) & set(help_options)
|
||||
|
||||
|
||||
class Main(Commands):
|
||||
"""The top-level group. Its help shows the banner, because its callback does not run for --help."""
|
||||
|
||||
@@ -54,7 +79,8 @@ class Main(Commands):
|
||||
@click.command(cls=Main, invoke_without_command=True, context_settings=context_settings)
|
||||
@click.option("-v", "--version", is_flag=True, default=False, help="Print version information.")
|
||||
@click.option("-d", "--debug", is_flag=True, default=False, help="Enable DEBUG level logs and JSON debug logging.")
|
||||
def main(version: bool, debug: bool) -> None:
|
||||
@click.pass_context
|
||||
def main(ctx: click.Context, version: bool, debug: bool) -> None:
|
||||
"""unshackle: Modular Movie, TV, and Music Archival Software."""
|
||||
debug_logging_enabled = debug or config.debug
|
||||
|
||||
@@ -89,7 +115,14 @@ def main(version: bool, debug: bool) -> None:
|
||||
if "--quiet" in serve_args or "-q" in serve_args:
|
||||
return
|
||||
|
||||
print_banner()
|
||||
if pins_banner(ctx.invoked_subcommand, sys.argv[1:]):
|
||||
pinned = PinnedLive(banner(), console)
|
||||
pinned.start(refresh=True)
|
||||
ctx.call_on_close(pinned.close)
|
||||
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
|
||||
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit(128 + signum))
|
||||
else:
|
||||
print_banner()
|
||||
|
||||
if version:
|
||||
return
|
||||
|
||||
@@ -102,6 +102,7 @@ class Config:
|
||||
wvds = data / "WVDs"
|
||||
prds = data / "PRDs"
|
||||
dcsl = data / "DCSL"
|
||||
themes = data / "themes" / "custom"
|
||||
|
||||
class _Filenames:
|
||||
# default filenames, do not modify here, set via config
|
||||
|
||||
+375
-69
@@ -4,17 +4,29 @@ import logging
|
||||
import math
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
import unicodedata
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
from functools import lru_cache
|
||||
from types import ModuleType
|
||||
from typing import IO, Any, Callable, Iterable, List, Literal, Mapping, Optional, TextIO, Union
|
||||
from typing import IO, Any, Callable, Iterable, Iterator, List, Literal, Mapping, Optional, TextIO, Union
|
||||
|
||||
import rich.cells
|
||||
from rich import box
|
||||
from rich._log_render import FormatTimeCallable, LogRender
|
||||
from rich.cells import cell_len
|
||||
from rich.color import Color, blend_rgb
|
||||
from rich.console import Console, ConsoleOptions, ConsoleRenderable, HighlighterType, RenderableType, RenderResult
|
||||
from rich.console import (
|
||||
Console,
|
||||
ConsoleOptions,
|
||||
ConsoleRenderable,
|
||||
Group,
|
||||
HighlighterType,
|
||||
RenderableType,
|
||||
RenderResult,
|
||||
)
|
||||
from rich.control import Control
|
||||
from rich.emoji import EmojiVariant
|
||||
from rich.highlighter import Highlighter, ReprHighlighter
|
||||
from rich.live import Live
|
||||
@@ -23,6 +35,8 @@ from rich.measure import Measurement
|
||||
from rich.padding import Padding, PaddingDimensions
|
||||
from rich.panel import Panel
|
||||
from rich.progress import BarColumn, Task
|
||||
from rich.rule import Rule
|
||||
from rich.segment import ControlType, Segment, SegmentLines, Segments
|
||||
from rich.status import Status
|
||||
from rich.style import Style, StyleType
|
||||
from rich.table import Table
|
||||
@@ -30,7 +44,7 @@ from rich.text import Text, TextType
|
||||
from rich.theme import Theme
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.themes import DEFAULT_THEME, PALETTES, apply_help_theme, resolve_palette
|
||||
from unshackle.core.themes import apply_help_theme, build_console_theme, load_active_theme
|
||||
|
||||
|
||||
class ComfyLogRenderer(LogRender):
|
||||
@@ -311,7 +325,8 @@ class ComfyConsole(Console):
|
||||
# We copy the list because stop() will modify console._live_stack.
|
||||
active_lives = list(self._live_stack)
|
||||
|
||||
for live in active_lives:
|
||||
# newest first: Rich's stop() pops the top of the stack
|
||||
for live in reversed(active_lives):
|
||||
live.stop()
|
||||
|
||||
try:
|
||||
@@ -323,72 +338,379 @@ class ComfyConsole(Console):
|
||||
stream=stream,
|
||||
)
|
||||
finally:
|
||||
for live in reversed(active_lives):
|
||||
for live in active_lives:
|
||||
live.start()
|
||||
|
||||
|
||||
primary_scheme = resolve_palette(config.theme)
|
||||
if primary_scheme is None:
|
||||
logging.getLogger("console").warning(
|
||||
"Unknown theme %r, falling back to %s (available: %s)",
|
||||
config.theme,
|
||||
DEFAULT_THEME,
|
||||
", ".join(PALETTES),
|
||||
)
|
||||
primary_scheme = dict(PALETTES[DEFAULT_THEME])
|
||||
active_theme, (primary_scheme, theme_styles, theme_gradients) = load_active_theme(config.theme)
|
||||
apply_help_theme(primary_scheme)
|
||||
primary_scheme["none"] = primary_scheme["text"]
|
||||
primary_scheme["grey23"] = primary_scheme["black"]
|
||||
primary_scheme["magenta"] = primary_scheme["pink"]
|
||||
primary_scheme["bright_red"] = primary_scheme["red"]
|
||||
primary_scheme["bright_green"] = primary_scheme["green"]
|
||||
primary_scheme["bright_yellow"] = primary_scheme["yellow"]
|
||||
primary_scheme["bright_blue"] = primary_scheme["blue"]
|
||||
primary_scheme["bright_magenta"] = primary_scheme["pink"]
|
||||
primary_scheme["bright_cyan"] = primary_scheme["cyan"]
|
||||
if config.set_terminal_bg:
|
||||
primary_scheme["none"] += f" on {primary_scheme['bg']}"
|
||||
|
||||
custom_colors = {"ascii.art": primary_scheme["pink"]}
|
||||
if config.set_terminal_bg:
|
||||
custom_colors["ascii.art"] += f" on {primary_scheme['bg']}"
|
||||
|
||||
@contextmanager
|
||||
def use_gradients(gradients: dict[str, Any]) -> Iterator[None]:
|
||||
"""Draw with another theme's gradients for the duration, as `env theme NAME` does."""
|
||||
global theme_gradients
|
||||
saved, theme_gradients = theme_gradients, gradients
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
theme_gradients = saved
|
||||
|
||||
|
||||
@lru_cache(maxsize=32)
|
||||
def gradient_lut(stops: tuple[str, ...], size: int = 64, cyclic: bool = False) -> list[Style]:
|
||||
"""Blend colour stops into *size* evenly spaced styles. *cyclic* blends the last stop back into the first."""
|
||||
colours = [Color.parse(stop).get_truecolor() for stop in stops]
|
||||
if cyclic:
|
||||
colours.append(colours[0])
|
||||
if len(colours) == 1:
|
||||
return [Style(color=Color.from_triplet(colours[0]))]
|
||||
lut = []
|
||||
for i in range(size):
|
||||
t = i / (size - 1) * (len(colours) - 1)
|
||||
n = min(int(t), len(colours) - 2)
|
||||
lut.append(Style(color=Color.from_triplet(blend_rgb(colours[n], colours[n + 1], t - n))))
|
||||
return lut
|
||||
|
||||
|
||||
class Gradient:
|
||||
"""Draw *renderable*, then recolour the cells drawn in *style*'s colour along the theme's *surface* gradient.
|
||||
|
||||
With *frame_only*, only the box-drawing characters on the outer edge change, so a panel's title and the lines inside
|
||||
keep their colours, even a tree guide drawn in the border's colour. Each recoloured cell carries its place along the
|
||||
gradient in its style's meta, so `slide_gradients` can animate the drawn lines.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
renderable: RenderableType,
|
||||
surface: str,
|
||||
style: StyleType,
|
||||
frame_only: bool = False,
|
||||
direction: Optional[str] = None,
|
||||
) -> None:
|
||||
self.renderable = renderable
|
||||
self.surface = surface
|
||||
self.style = style
|
||||
self.frame_only = frame_only
|
||||
self.direction = direction
|
||||
|
||||
def __rich_console__(self, console: Console, options: ConsoleOptions) -> RenderResult:
|
||||
stops = theme_gradients.get(self.surface)
|
||||
if not stops:
|
||||
yield self.renderable
|
||||
return
|
||||
colour = console.get_style(self.style).color
|
||||
lines = console.render_lines(self.renderable, options, pad=False, new_lines=True)
|
||||
|
||||
def candidate(segment: Segment) -> bool:
|
||||
return not segment.control and segment.style is not None and segment.style.color == colour
|
||||
|
||||
def characters(line: list[Segment]) -> Iterator[tuple[int, Segment, str]]:
|
||||
x = 0
|
||||
for segment in line:
|
||||
for character in segment.text if candidate(segment) else [segment.text]:
|
||||
yield x, segment, character
|
||||
x += cell_len(character)
|
||||
|
||||
marks = [
|
||||
(x, y, character)
|
||||
for y, line in enumerate(lines)
|
||||
for x, segment, character in characters(line)
|
||||
if candidate(segment) and character.strip()
|
||||
]
|
||||
cells = {(x, y) for x, y, _ in marks}
|
||||
if self.frame_only:
|
||||
boxes = [(x, y) for x, y, character in marks if "─" <= character <= "╿"]
|
||||
ends = (min(y for _, y in boxes), max(y for _, y in boxes)) if boxes else ()
|
||||
left: dict[int, int] = {}
|
||||
right: dict[int, int] = {}
|
||||
for x, y in boxes:
|
||||
left[y], right[y] = min(left.get(y, x), x), max(right.get(y, x), x)
|
||||
cells = {(x, y) for x, y in boxes if y in ends or x in (left[y], right[y])}
|
||||
if not cells:
|
||||
yield from (segment for line in lines for segment in line)
|
||||
return
|
||||
x0, y0 = min(x for x, _ in cells), min(y for _, y in cells)
|
||||
direction = self.direction or theme_gradients.get("direction", "horizontal")
|
||||
|
||||
def distance(x: int, y: int) -> int:
|
||||
return {"horizontal": x - x0, "vertical": y - y0}.get(direction, x - x0 + 2 * (y - y0))
|
||||
|
||||
span = max(distance(x, y) for x, y in cells) or 1
|
||||
lut = gradient_lut(stops)
|
||||
|
||||
def recoloured() -> Iterator[Segment]:
|
||||
for y, line in enumerate(lines):
|
||||
for x, segment, character in characters(line):
|
||||
if candidate(segment) and (x, y) in cells:
|
||||
t = distance(x, y) / span
|
||||
tint = lut[round(t * (len(lut) - 1))] + Style(meta={"gradient": (self.surface, t)})
|
||||
yield Segment(character, (segment.style or Style.null()) + tint)
|
||||
elif candidate(segment):
|
||||
yield Segment(character, segment.style)
|
||||
else:
|
||||
yield segment
|
||||
|
||||
yield from Segment.simplify(recoloured())
|
||||
|
||||
def __rich_measure__(self, console: Console, options: ConsoleOptions) -> Measurement:
|
||||
return Measurement.get(console, options, self.renderable)
|
||||
|
||||
|
||||
def slide_gradients(lines: list[list[Segment]], offset: float) -> list[list[Segment]]:
|
||||
"""Slide the gradient colours that `Gradient` drew into *lines* along by *offset* gradient lengths, looping the last
|
||||
stop back into the first, so a sequence of offsets animates them. Other cells keep their colours."""
|
||||
return [[_slid(segment, offset) for segment in line] for line in lines]
|
||||
|
||||
|
||||
def _slid(segment: Segment, offset: float) -> Segment:
|
||||
mark = _gradient_mark(segment.style) if segment.style else None
|
||||
stops = theme_gradients.get(mark[0]) if mark else None
|
||||
if not mark or not stops or segment.style is None:
|
||||
return segment
|
||||
lut = gradient_lut(stops, cyclic=True)
|
||||
return Segment(segment.text, segment.style + lut[round((mark[1] - offset) % 1 * (len(lut) - 1))])
|
||||
|
||||
|
||||
@lru_cache(maxsize=4096)
|
||||
def _gradient_mark(style: Style) -> Optional[tuple[str, float]]:
|
||||
"""The surface and the place along it of a cell that `Gradient` coloured, or None."""
|
||||
return style.meta.get("gradient") if style._meta else None
|
||||
|
||||
|
||||
class _Drawn:
|
||||
"""A renderable that draws *target* with Rich's own, unpatched *render* method."""
|
||||
|
||||
def __init__(self, render: Callable[..., RenderResult], target: Any) -> None:
|
||||
self.render = render
|
||||
self.target = target
|
||||
|
||||
def __rich_console__(self, console: Console, options: ConsoleOptions) -> RenderResult:
|
||||
return self.render(self.target, console, options)
|
||||
|
||||
|
||||
def _paint_with(
|
||||
render: Callable[..., RenderResult], surface: str, style_attribute: str, direction: Optional[str] = None
|
||||
) -> Callable[..., RenderResult]:
|
||||
"""Wrap a Rich class's render method so the theme's *surface* gradient colours its lines."""
|
||||
|
||||
def __rich_console__(self: Any, console: Console, options: ConsoleOptions) -> RenderResult:
|
||||
if not theme_gradients.get(surface):
|
||||
return render(self, console, options)
|
||||
gradient = Gradient(_Drawn(render, self), surface, getattr(self, style_attribute), True, direction)
|
||||
return gradient.__rich_console__(console, options)
|
||||
|
||||
return __rich_console__
|
||||
|
||||
|
||||
Rule.__rich_console__ = _paint_with(Rule.__rich_console__, "rule", "style", "horizontal") # type: ignore[method-assign]
|
||||
Panel.__rich_console__ = _paint_with(Panel.__rich_console__, "panel", "border_style") # type: ignore[method-assign]
|
||||
|
||||
_SYNC_BEGIN = Segments([Segment("\x1b[?2026h", None, [(ControlType.BELL,)])])
|
||||
_SYNC_END = Segments([Segment("\x1b[?2026l", None, [(ControlType.BELL,)])])
|
||||
|
||||
|
||||
class SyncLive(Live):
|
||||
"""Live that wraps each repaint in DEC 2026 begin/end-sync so the terminal draws it as one atomic frame."""
|
||||
"""Live that wraps each repaint, and each print while it runs, in DEC 2026 begin/end-sync, so the terminal draws
|
||||
the frame as one."""
|
||||
|
||||
def refresh(self) -> None:
|
||||
if not self.console.is_terminal:
|
||||
super().refresh()
|
||||
return
|
||||
self.console.file.write("\x1b[?2026h")
|
||||
try:
|
||||
super().refresh()
|
||||
finally:
|
||||
self.console.file.write("\x1b[?2026l")
|
||||
self.console.file.flush()
|
||||
def process_renderables(self, renderables: list[ConsoleRenderable]) -> list[ConsoleRenderable]:
|
||||
return self.synced(super().process_renderables(renderables))
|
||||
|
||||
def synced(self, renderables: list[ConsoleRenderable]) -> list[ConsoleRenderable]:
|
||||
if not self.console.is_interactive or self.console.legacy_windows:
|
||||
return renderables
|
||||
return [_SYNC_BEGIN, *renderables, _SYNC_END]
|
||||
|
||||
|
||||
class PinnedLive(SyncLive):
|
||||
"""A root live area that holds the screen for a whole command: *header* at the top, the newest output under it,
|
||||
and the nested live areas (spinners, progress bars) at the bottom.
|
||||
|
||||
It keeps what is printed while it runs, and sends the oldest lines to the scrollback above the live area once the
|
||||
screen is full, so they scroll off the top. The header goes to the scrollback first, so the scrollback ends up as a
|
||||
plain run would leave it. On screen, the gradients in the header and the kept lines move.
|
||||
"""
|
||||
|
||||
LOOP_SECONDS = 4.0
|
||||
|
||||
def __init__(self, header: RenderableType, live_console: Console) -> None:
|
||||
super().__init__(console=live_console, transient=True, refresh_per_second=20)
|
||||
self.header = header
|
||||
self.header_lines: tuple[int, list[list[Segment]]] = (-1, [])
|
||||
self.kept: list[list[Segment]] = []
|
||||
self.room = live_console.size.height
|
||||
self.header_sent = False
|
||||
self.started_at = time.monotonic()
|
||||
|
||||
@staticmethod
|
||||
def wanted(live_console: Console) -> bool:
|
||||
"""Whether the terminal can show the moving header: interactive, with colour, and wide enough."""
|
||||
colour = live_console.color_system is not None and not live_console.no_color
|
||||
return live_console.is_interactive and colour and fits_terminal(live_console)
|
||||
|
||||
@property
|
||||
def renderable(self) -> RenderableType:
|
||||
return _PinnedScreen(self)
|
||||
|
||||
def process_renderables(self, renderables: list[ConsoleRenderable]) -> list[ConsoleRenderable]:
|
||||
if not self.console.is_interactive:
|
||||
return super().process_renderables(renderables)
|
||||
with self._lock:
|
||||
printed = [renderable for renderable in renderables if not isinstance(renderable, Control)]
|
||||
capture = [_Capture(self, printed)] if printed else []
|
||||
return self.synced([self._live_render.position_cursor(), *capture, self._live_render])
|
||||
|
||||
def head(self, options: ConsoleOptions) -> list[list[Segment]]:
|
||||
"""The header's lines, drawn once for each width."""
|
||||
width, lines = self.header_lines
|
||||
if width != options.max_width:
|
||||
lines = self.console.render_lines(self.header, options, pad=False)
|
||||
self.header_lines = (options.max_width, lines)
|
||||
return lines
|
||||
|
||||
def overflow(self) -> list[list[Segment]]:
|
||||
"""Take off the oldest kept lines that no longer fit on the screen. Call it with the lock held."""
|
||||
count = max(0, len(self.kept) - self.room)
|
||||
out = self.kept[:count]
|
||||
del self.kept[:count]
|
||||
return out
|
||||
|
||||
def still(self, lines: list[list[Segment]]) -> list[RenderableType]:
|
||||
"""*lines* for the scrollback, after the header if it has not gone there yet."""
|
||||
out: list[RenderableType] = [] if self.header_sent else [self.header]
|
||||
self.header_sent = True
|
||||
return [*out, SegmentLines(lines, new_lines=True)]
|
||||
|
||||
def close(self) -> None:
|
||||
"""Stop the live area, then print what is still kept."""
|
||||
self.stop()
|
||||
with self._lock:
|
||||
kept, self.kept = self.kept, []
|
||||
for renderable in self.still(kept):
|
||||
self.console.print(renderable, crop=False)
|
||||
|
||||
|
||||
class _Capture:
|
||||
"""The output of one print while PinnedLive runs. Rendered with the print's own options, it keeps the lines in
|
||||
PinnedLive and yields only the oldest kept lines that no longer fit, which land above the live area."""
|
||||
|
||||
def __init__(self, live: PinnedLive, renderables: list[ConsoleRenderable]) -> None:
|
||||
self.live = live
|
||||
self.renderables = renderables
|
||||
|
||||
def __rich_console__(self, console: Console, options: ConsoleOptions) -> RenderResult:
|
||||
lines = [
|
||||
line for renderable in self.renderables for line in console.render_lines(renderable, options, pad=False)
|
||||
]
|
||||
with self.live._lock:
|
||||
self.live.kept.extend(lines)
|
||||
flushed = self.live.overflow()
|
||||
if flushed:
|
||||
yield from self.live.still(flushed)
|
||||
|
||||
|
||||
class _PinnedScreen:
|
||||
def __init__(self, live: PinnedLive) -> None:
|
||||
self.live = live
|
||||
|
||||
def __rich_console__(self, console: Console, options: ConsoleOptions) -> RenderResult:
|
||||
offset = (time.monotonic() - self.live.started_at) / self.live.LOOP_SECONDS
|
||||
head = self.live.head(options)
|
||||
nested = [live.get_renderable() for live in console._live_stack[1:]]
|
||||
foot = console.render_lines(Group(*nested), options, pad=False) if nested else []
|
||||
room = self.live.room = max(0, console.size.height - len(head) - len(foot))
|
||||
body = self.live.kept[-room:] if room else []
|
||||
for line in slide_gradients([*head, *body], offset) + foot:
|
||||
yield from Segment.adjust_line_length(line, options.max_width, pad=False)
|
||||
yield Segment.line()
|
||||
|
||||
|
||||
PULSE_PERIOD = 40.0
|
||||
PULSE_SPEED = 15.0 # cells a second
|
||||
|
||||
|
||||
def fits_terminal(live_console: Console) -> bool:
|
||||
"""Whether the terminal is at least as wide as *live_console*. A live area that wraps leaves old frames behind,
|
||||
because Rich moves the cursor up by the lines it drew, not by the rows the terminal used."""
|
||||
return shutil.get_terminal_size((live_console.width, 0)).columns >= live_console.width
|
||||
|
||||
|
||||
def bar_gradients(palette: Mapping[str, str]) -> tuple[bool, Optional[list[Style]], list[Style]]:
|
||||
"""The progress bar colours of the gradients in use: whether they scroll, the fill (None without a `bar`
|
||||
gradient) and the pulse, which without a `pulse` gradient blends *palette*'s dark_gray into its pink."""
|
||||
scroll = theme_gradients.get("motion") == "scroll"
|
||||
bar = theme_gradients.get("bar")
|
||||
pulse = gradient_lut(theme_gradients.get("pulse") or (palette["dark_gray"], palette["pink"]))
|
||||
return scroll, gradient_lut(bar, cyclic=scroll) if bar else None, pulse
|
||||
|
||||
|
||||
class GradientPulseBarColumn(BarColumn):
|
||||
LUT_SIZE = 32
|
||||
|
||||
def __init__(self, *args: Any, pulse_period: float = 40.0, pulse_speed: float = 15.0, **kwargs: Any) -> None:
|
||||
def __init__(
|
||||
self, *args: Any, pulse_period: float = PULSE_PERIOD, pulse_speed: float = PULSE_SPEED, **kwargs: Any
|
||||
) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
self.pulse_period = pulse_period
|
||||
self.pulse_speed = pulse_speed
|
||||
lo = Color.parse(primary_scheme["dark_gray"]).triplet
|
||||
hi = Color.parse(primary_scheme["pink"]).triplet
|
||||
assert lo and hi
|
||||
self._lut = [
|
||||
Style(color=Color.from_triplet(blend_rgb(lo, hi, i / (self.LUT_SIZE - 1)))) for i in range(self.LUT_SIZE)
|
||||
]
|
||||
self.scroll, self._fill_lut, self._lut = bar_gradients(primary_scheme)
|
||||
|
||||
def render(self, task: Task) -> RenderableType: # type: ignore[override]
|
||||
if task.started and task.total is not None:
|
||||
return super().render(task)
|
||||
if self._fill_lut is None or task.completed >= task.total:
|
||||
return super().render(task)
|
||||
fraction = min(1.0, max(0.0, task.completed / task.total)) if task.total else 1.0
|
||||
offset = task.get_time() * self.pulse_speed if self.scroll else None
|
||||
return _GradientFill(self._fill_lut, fraction, offset, self.bar_width, self.style)
|
||||
return _GradientPulse(self._lut, task.get_time() * self.pulse_speed, self.pulse_period, self.bar_width)
|
||||
|
||||
|
||||
def gradient_fill(
|
||||
lut: list[Style],
|
||||
fraction: float,
|
||||
width: int,
|
||||
offset: Optional[float],
|
||||
back: Optional[StyleType],
|
||||
ascii: bool = False,
|
||||
) -> Text:
|
||||
"""Draw a progress bar *fraction* full, with the gradient fixed along the bar or, given an *offset*, slid along it."""
|
||||
full, half = divmod(int(width * 2 * fraction), 2)
|
||||
bar = Text()
|
||||
for i in range(full + half):
|
||||
t = i / max(1, width - 1) if offset is None else (i - offset) / width % 1
|
||||
character = ("-" if ascii else "━") if i < full else (" " if ascii else "╸")
|
||||
bar.append(character, lut[round(t * (len(lut) - 1))])
|
||||
remaining = width - full - half
|
||||
if remaining and back is not None:
|
||||
if not half and full:
|
||||
bar.append(" " if ascii else "╺", back)
|
||||
remaining -= 1
|
||||
bar.append(("-" if ascii else "━") * remaining, back)
|
||||
return bar
|
||||
|
||||
|
||||
class _GradientFill:
|
||||
def __init__(
|
||||
self, lut: list[Style], fraction: float, offset: Optional[float], width: Optional[int], back: StyleType
|
||||
) -> None:
|
||||
self.lut = lut
|
||||
self.fraction = fraction
|
||||
self.offset = offset
|
||||
self.width = width
|
||||
self.back = back
|
||||
|
||||
def __rich_console__(self, console: Console, options: ConsoleOptions) -> RenderResult:
|
||||
width = min(self.width or options.max_width, options.max_width)
|
||||
# as ProgressBar: without colour the empty part would look full
|
||||
back = self.back if not console.no_color and console.color_system is not None else None
|
||||
yield gradient_fill(
|
||||
self.lut, self.fraction, width, self.offset, back, options.legacy_windows or options.ascii_only
|
||||
)
|
||||
|
||||
def __rich_measure__(self, console: Console, options: ConsoleOptions) -> Measurement:
|
||||
return Measurement(self.width, self.width) if self.width is not None else Measurement(4, options.max_width)
|
||||
|
||||
|
||||
class _GradientPulse:
|
||||
def __init__(self, lut: list[Style], offset: float, period: float, width: Optional[int]) -> None:
|
||||
self.lut = lut
|
||||
@@ -433,26 +755,7 @@ console = ComfyConsole(
|
||||
log_time=False,
|
||||
log_path=False,
|
||||
width=80,
|
||||
theme=Theme(
|
||||
{
|
||||
"bar.back": primary_scheme["dark_gray"],
|
||||
"bar.complete": primary_scheme["pink"],
|
||||
"bar.finished": primary_scheme["green"],
|
||||
"bar.pulse": primary_scheme["pink"],
|
||||
"black": primary_scheme["black"],
|
||||
"inspect.async_def": f"italic {primary_scheme['cyan']}",
|
||||
"progress.data.speed": "dark_orange",
|
||||
"repr.number": f"bold not italic {primary_scheme['cyan']}",
|
||||
"repr.number_complex": f"bold not italic {primary_scheme['cyan']}",
|
||||
"rule.line": primary_scheme["dark_gray"],
|
||||
"rule.text": primary_scheme["pink"],
|
||||
"tree.line": primary_scheme["dark_gray"],
|
||||
"status.spinner": primary_scheme["pink"],
|
||||
"progress.spinner": primary_scheme["pink"],
|
||||
**primary_scheme,
|
||||
**custom_colors,
|
||||
}
|
||||
),
|
||||
theme=build_console_theme(primary_scheme, theme_styles, config.set_terminal_bg),
|
||||
log_renderer=ComfyLogRenderer(show_time=False, show_path=False),
|
||||
)
|
||||
|
||||
@@ -524,7 +827,9 @@ __all__ = (
|
||||
"ComfyLogRenderer",
|
||||
"ComfyRichHandler",
|
||||
"ComfyConsole",
|
||||
"Gradient",
|
||||
"GradientPulseBarColumn",
|
||||
"PinnedLive",
|
||||
"SyncLive",
|
||||
"console",
|
||||
"listing_panel",
|
||||
@@ -534,4 +839,5 @@ __all__ = (
|
||||
"set_notice_handler",
|
||||
"set_prompt_handler",
|
||||
"show_notice",
|
||||
"use_gradients",
|
||||
)
|
||||
|
||||
+235
-174
@@ -1,200 +1,261 @@
|
||||
"""
|
||||
Named CLI colour themes.
|
||||
CLI colour themes, read from YAML files.
|
||||
|
||||
Each palette maps the same role keys to colors: `text`/`text2` for body copy, `pink` for the
|
||||
brand accent, the six ANSI hues, and the grey ramp used for rules and dim details. The active
|
||||
palette drives both the rich Console theme (banner, logs, progress) and the click help screens,
|
||||
so a single `theme` config value restyles the whole CLI.
|
||||
A theme sets the colours of the `ROLES`, can override any Rich style under `styles:`, and can draw the
|
||||
`GRADIENT_SURFACES` in blended colours under `gradients:`. The shipped themes are in `unshackle/themes/`. A file in `directories.themes` adds a theme, or replaces a shipped
|
||||
theme with the same name. The active theme drives both the rich Console theme (banner, logs,
|
||||
progress) and the click help screens.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
from rich.color import Color, ColorParseError
|
||||
from rich.errors import StyleSyntaxError
|
||||
from rich.style import Style
|
||||
from rich.theme import Theme
|
||||
from rich_click import RichHelpConfiguration
|
||||
|
||||
DEFAULT_THEME = "catppuccin-mocha"
|
||||
|
||||
PALETTES: dict[str, dict[str, str]] = {
|
||||
# Colors based on "CatppuccinMocha" from Gogh themes
|
||||
"catppuccin-mocha": {
|
||||
"bg": "rgb(30,30,46)",
|
||||
"text": "rgb(205,214,244)",
|
||||
"text2": "rgb(162,169,193)",
|
||||
"black": "rgb(69,71,90)",
|
||||
"bright_black": "rgb(88,91,112)",
|
||||
"red": "rgb(243,139,168)",
|
||||
"green": "rgb(166,227,161)",
|
||||
"yellow": "rgb(249,226,175)",
|
||||
"blue": "rgb(137,180,250)",
|
||||
"pink": "rgb(245,194,231)",
|
||||
"cyan": "rgb(148,226,213)",
|
||||
"gray": "rgb(166,173,200)",
|
||||
"bright_gray": "rgb(186,194,222)",
|
||||
"dark_gray": "rgb(54,54,84)",
|
||||
},
|
||||
# draculatheme.com spec; purple stands in for blue, comment for the dim grays
|
||||
"dracula": {
|
||||
"bg": "#282a36",
|
||||
"text": "#f8f8f2",
|
||||
"text2": "#b8bfd8",
|
||||
"black": "#21222c",
|
||||
"bright_black": "#6272a4",
|
||||
"red": "#ff5555",
|
||||
"green": "#50fa7b",
|
||||
"yellow": "#f1fa8c",
|
||||
"blue": "#bd93f9",
|
||||
"pink": "#ff79c6",
|
||||
"cyan": "#8be9fd",
|
||||
"gray": "#6272a4",
|
||||
"bright_gray": "#e9e9f4",
|
||||
"dark_gray": "#44475a",
|
||||
},
|
||||
# nordtheme.com: polar night / snow storm / frost / aurora
|
||||
"nord": {
|
||||
"bg": "#2e3440",
|
||||
"text": "#d8dee9",
|
||||
"text2": "#9aa4b8",
|
||||
"black": "#3b4252",
|
||||
"bright_black": "#4c566a",
|
||||
"red": "#bf616a",
|
||||
"green": "#a3be8c",
|
||||
"yellow": "#ebcb8b",
|
||||
"blue": "#81a1c1",
|
||||
"pink": "#b48ead",
|
||||
"cyan": "#88c0d0",
|
||||
"gray": "#616e88",
|
||||
"bright_gray": "#e5e9f0",
|
||||
"dark_gray": "#434c5e",
|
||||
},
|
||||
# github.com/morhetz/gruvbox dark, bright variants
|
||||
"gruvbox": {
|
||||
"bg": "#282828",
|
||||
"text": "#ebdbb2",
|
||||
"text2": "#bdae93",
|
||||
"black": "#504945",
|
||||
"bright_black": "#665c54",
|
||||
"red": "#fb4934",
|
||||
"green": "#b8bb26",
|
||||
"yellow": "#fabd2f",
|
||||
"blue": "#83a598",
|
||||
"pink": "#d3869b",
|
||||
"cyan": "#8ec07c",
|
||||
"gray": "#928374",
|
||||
"bright_gray": "#d5c4a1",
|
||||
"dark_gray": "#3c3836",
|
||||
},
|
||||
# Atom One Dark syntax palette
|
||||
"one-dark": {
|
||||
"bg": "#282c34",
|
||||
"text": "#abb2bf",
|
||||
"text2": "#818896",
|
||||
"black": "#3b4048",
|
||||
"bright_black": "#5c6370",
|
||||
"red": "#e06c75",
|
||||
"green": "#98c379",
|
||||
"yellow": "#e5c07b",
|
||||
"blue": "#61afef",
|
||||
"pink": "#c678dd",
|
||||
"cyan": "#56b6c2",
|
||||
"gray": "#5c6370",
|
||||
"bright_gray": "#c8ccd4",
|
||||
"dark_gray": "#3e4451",
|
||||
},
|
||||
# github.com/enkia/tokyo-night-vscode-theme, night variant
|
||||
"tokyo-night": {
|
||||
"bg": "#1a1b26",
|
||||
"text": "#c0caf5",
|
||||
"text2": "#a9b1d6",
|
||||
"black": "#15161e",
|
||||
"bright_black": "#414868",
|
||||
"red": "#f7768e",
|
||||
"green": "#9ece6a",
|
||||
"yellow": "#e0af68",
|
||||
"blue": "#7aa2f7",
|
||||
"pink": "#bb9af7",
|
||||
"cyan": "#7dcfff",
|
||||
"gray": "#565f89",
|
||||
"bright_gray": "#a9b1d6",
|
||||
"dark_gray": "#292e42",
|
||||
},
|
||||
# classic Monokai; purple stands in for pink, 66d9ef doubles as blue
|
||||
"monokai": {
|
||||
"bg": "#272822",
|
||||
"text": "#f8f8f2",
|
||||
"text2": "#cfcfc2",
|
||||
"black": "#2e2e2e",
|
||||
"bright_black": "#75715e",
|
||||
"red": "#f92672",
|
||||
"green": "#a6e22e",
|
||||
"yellow": "#e6db74",
|
||||
"blue": "#66d9ef",
|
||||
"pink": "#ae81ff",
|
||||
"cyan": "#a1efe4",
|
||||
"gray": "#a59f85",
|
||||
"bright_gray": "#cfcfc2",
|
||||
"dark_gray": "#3e3d32",
|
||||
},
|
||||
# flexoki.com dark, 400-level accents
|
||||
"flexoki": {
|
||||
"bg": "#100f0f",
|
||||
"text": "#cecdc3",
|
||||
"text2": "#878580",
|
||||
"black": "#282726",
|
||||
"bright_black": "#403e3c",
|
||||
"red": "#d14d41",
|
||||
"green": "#879a39",
|
||||
"yellow": "#d0a215",
|
||||
"blue": "#4385be",
|
||||
"pink": "#ce5d97",
|
||||
"cyan": "#3aa99f",
|
||||
"gray": "#6f6e69",
|
||||
"bright_gray": "#b7b5ac",
|
||||
"dark_gray": "#343331",
|
||||
},
|
||||
# ethanschoonover.com/solarized dark; magenta stands in for pink
|
||||
"solarized-dark": {
|
||||
"bg": "#002b36",
|
||||
"text": "#839496",
|
||||
"text2": "#586e75",
|
||||
"black": "#073642",
|
||||
"bright_black": "#586e75",
|
||||
"red": "#dc322f",
|
||||
"green": "#859900",
|
||||
"yellow": "#b58900",
|
||||
"blue": "#268bd2",
|
||||
"pink": "#d33682",
|
||||
"cyan": "#2aa198",
|
||||
"gray": "#657b83",
|
||||
"bright_gray": "#93a1a1",
|
||||
"dark_gray": "#073642",
|
||||
},
|
||||
}
|
||||
from unshackle.core.config import config
|
||||
|
||||
DEFAULT_THEME = "unshackle"
|
||||
ALIASES = {
|
||||
"default": DEFAULT_THEME,
|
||||
"catppuccin": DEFAULT_THEME,
|
||||
"mocha": DEFAULT_THEME,
|
||||
"catppuccin": "catppuccin-mocha",
|
||||
"mocha": "catppuccin-mocha",
|
||||
"onedark": "one-dark",
|
||||
"tokyonight": "tokyo-night",
|
||||
"solarized": "solarized-dark",
|
||||
"tokyonight": "tokyo-night",
|
||||
}
|
||||
|
||||
ROLES = (
|
||||
"bg",
|
||||
"text",
|
||||
"text2",
|
||||
"black",
|
||||
"bright_black",
|
||||
"red",
|
||||
"green",
|
||||
"yellow",
|
||||
"blue",
|
||||
"pink",
|
||||
"cyan",
|
||||
"gray",
|
||||
"bright_gray",
|
||||
"dark_gray",
|
||||
)
|
||||
ROLE_ALIASES = {"accent": "pink"}
|
||||
PRESETS_DIR = Path(__file__).resolve().parent.parent / "themes"
|
||||
FILE_KEYS = {*ROLES, *ROLE_ALIASES, "extends", "styles", "gradients", "author", "description"}
|
||||
GRADIENT_SURFACES = ("banner", "bar", "pulse", "rule", "panel")
|
||||
GRADIENT_OPTIONS = {"direction": ("horizontal", "vertical", "diagonal"), "motion": ("static", "scroll")}
|
||||
|
||||
def resolve_palette(name: object) -> dict[str, str] | None:
|
||||
"""Look up a palette by theme name or alias, case-insensitively.
|
||||
ThemeData = tuple[dict[str, str], dict[str, str], dict[str, Any]]
|
||||
|
||||
Takes any YAML scalar, because unshackle does not validate config values. A non-string
|
||||
never matches a palette name.
|
||||
Returns a copy: console.py extends the active palette in place, and that must
|
||||
not pollute the master definitions.
|
||||
|
||||
def normalize_name(name: object) -> str:
|
||||
"""Normalise a theme name or file stem: lowercase, with `_` read as `-`."""
|
||||
return str(name or "").strip().lower().replace("_", "-")
|
||||
|
||||
|
||||
def canonical_name(name: object) -> str:
|
||||
"""Normalise a theme name and resolve an alias to the theme it names."""
|
||||
key = normalize_name(name)
|
||||
return ALIASES.get(key, key)
|
||||
|
||||
|
||||
def theme_files(folder: Path) -> dict[str, Path]:
|
||||
"""Map each theme file's name to its path. It skips alias names, which belong to the shipped themes."""
|
||||
try:
|
||||
paths = sorted(path for path in folder.iterdir() if path.suffix.lower() in (".yaml", ".yml"))
|
||||
except OSError as e:
|
||||
if folder.exists():
|
||||
logging.getLogger("console").warning("cannot read the themes folder %s: %s", folder, e.strerror or e)
|
||||
return {}
|
||||
files: dict[str, Path] = {}
|
||||
for path in paths:
|
||||
name = normalize_name(path.stem)
|
||||
if name not in ALIASES and name.isprintable():
|
||||
files.setdefault(name, path)
|
||||
return files
|
||||
|
||||
|
||||
def shipped_themes() -> dict[str, Path]:
|
||||
return theme_files(PRESETS_DIR)
|
||||
|
||||
|
||||
def user_themes() -> dict[str, Path]:
|
||||
return theme_files(Path(config.directories.themes))
|
||||
|
||||
|
||||
def load_theme(name: object, user_files: bool = True) -> ThemeData:
|
||||
"""Resolve a theme name to its role colours and its `styles:` overrides.
|
||||
|
||||
A user file starts from its `extends` theme, else the shipped theme with the same name, else the
|
||||
default. That base is always a shipped file, so a theme that extends itself cannot loop.
|
||||
It checks every value, so `build_console_theme` always accepts the result. Raises ValueError,
|
||||
naming the file and the entry, when the theme is unknown or not valid.
|
||||
"""
|
||||
key = str(name or "").strip().lower().replace("_", "-")
|
||||
palette = PALETTES.get(ALIASES.get(key, key))
|
||||
return dict(palette) if palette else None
|
||||
key = canonical_name(name)
|
||||
shipped = shipped_themes()
|
||||
users = user_themes() if user_files else {}
|
||||
user = users.get(key)
|
||||
if user is None:
|
||||
if key not in shipped:
|
||||
raise ValueError(f"unknown theme {str(name)!r}")
|
||||
return apply_theme(shipped[key].name, read_theme_file(shipped[key]), {}, {}, {})
|
||||
|
||||
data = read_theme_file(user)
|
||||
extends = data.get("extends")
|
||||
if extends is not None and not isinstance(extends, str):
|
||||
raise ValueError(f"{user.name}: extends must be a quoted theme name")
|
||||
base = canonical_name(extends or (key if key in shipped else DEFAULT_THEME))
|
||||
if base not in shipped:
|
||||
raise ValueError(f"{user.name}: extends {data['extends']!r}, not a shipped theme")
|
||||
return apply_theme(user.name, data, *load_theme(base, user_files=False))
|
||||
|
||||
|
||||
def load_active_theme(name: object) -> tuple[str, ThemeData]:
|
||||
"""Load the configured theme, or the shipped default when it is unknown or not valid. Returns the name in use."""
|
||||
try:
|
||||
return canonical_name(name), load_theme(name)
|
||||
except ValueError as e:
|
||||
logging.getLogger("console").warning("%s, using the %s theme", e, DEFAULT_THEME)
|
||||
return DEFAULT_THEME, load_theme(DEFAULT_THEME, user_files=False)
|
||||
|
||||
|
||||
def read_theme_file(path: Path) -> dict[str, Any]:
|
||||
try:
|
||||
data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
|
||||
except (OSError, UnicodeDecodeError, RecursionError, yaml.YAMLError) as e:
|
||||
raise ValueError(f"{path.name}: cannot read: {shorten(' '.join(str(e).split()), 80)}") from e
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError(f"{path.name}: not a mapping of theme keys")
|
||||
unknown = sorted(str(key) for key in data if key not in FILE_KEYS)
|
||||
if unknown:
|
||||
raise ValueError(f"{path.name}: unknown key {', '.join(unknown)}")
|
||||
return data
|
||||
|
||||
|
||||
def apply_theme(
|
||||
file: str, data: dict[str, Any], palette: dict[str, str], styles: dict[str, str], gradients: dict[str, Any]
|
||||
) -> ThemeData:
|
||||
"""Lay the keys of a theme file over a base theme, and return the result. The base is not changed."""
|
||||
data = dict(data)
|
||||
for alias, role in ROLE_ALIASES.items():
|
||||
if alias in data:
|
||||
if role in data:
|
||||
raise ValueError(f"{file}: set {role} or {alias}, not both")
|
||||
data[role] = data.pop(alias)
|
||||
|
||||
palette = dict(palette)
|
||||
for role in ROLES:
|
||||
if role not in data:
|
||||
continue
|
||||
value = data[role]
|
||||
if value is None or value == "":
|
||||
raise ValueError(f"{file}: {role} is empty (put hex values in quotes)")
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(f"{file}: {role} must be a quoted colour")
|
||||
palette[role] = parse_colour(file, role, value, {})
|
||||
missing = [role for role in ROLES if role not in palette]
|
||||
if missing:
|
||||
raise ValueError(f"{file}: missing {', '.join(missing)}")
|
||||
|
||||
overrides = data.get("styles") or {}
|
||||
if not isinstance(overrides, dict):
|
||||
raise ValueError(f"{file}: styles must be a mapping")
|
||||
styles = dict(styles)
|
||||
for style_name, value in overrides.items():
|
||||
if not isinstance(style_name, str) or not isinstance(value, str):
|
||||
raise ValueError(f"{file}: styles: quote {shorten(str(style_name))} and its value")
|
||||
if style_name in ROLES or style_name in ROLE_ALIASES:
|
||||
raise ValueError(f"{file}: set {style_name} at the top level, not under styles")
|
||||
resolved = " ".join(palette.get(ROLE_ALIASES.get(word.lower(), word.lower()), word) for word in value.split())
|
||||
try:
|
||||
parsed = Style.parse(resolved)
|
||||
except (StyleSyntaxError, ValueError) as e:
|
||||
raise ValueError(f"{file}: styles: {style_name}: {shorten(value)} is not a Rich style") from e
|
||||
if parsed.link or parsed.conceal:
|
||||
raise ValueError(f"{file}: styles: {style_name}: link and conceal not allowed")
|
||||
styles[style_name] = resolved
|
||||
|
||||
overrides = data.get("gradients") or {}
|
||||
if not isinstance(overrides, dict):
|
||||
raise ValueError(f"{file}: gradients must be a mapping")
|
||||
gradients = dict(gradients)
|
||||
for key, value in overrides.items():
|
||||
if key in GRADIENT_OPTIONS:
|
||||
if not isinstance(value, str) or value not in GRADIENT_OPTIONS[key]:
|
||||
raise ValueError(f"{file}: gradients: {key} must be {' or '.join(GRADIENT_OPTIONS[key])}")
|
||||
gradients[key] = value
|
||||
elif key in GRADIENT_SURFACES:
|
||||
stops = [value] if isinstance(value, str) else value
|
||||
if not isinstance(stops, list) or not stops or not all(isinstance(stop, str) for stop in stops):
|
||||
raise ValueError(f"{file}: gradients: {key} must be a list of quoted colours")
|
||||
gradients[key] = tuple(parse_colour(file, f"gradients: {key}", stop, palette) for stop in stops)
|
||||
else:
|
||||
raise ValueError(f"{file}: gradients: unknown key {shorten(str(key))}")
|
||||
return palette, styles, gradients
|
||||
|
||||
|
||||
def parse_colour(file: str, label: str, value: str, palette: dict[str, str]) -> str:
|
||||
"""Check one colour from a theme file. A role name in *palette* becomes that role's colour."""
|
||||
value = palette.get(ROLE_ALIASES.get(value.lower(), value.lower()), value)
|
||||
value = "".join(value.split())
|
||||
try:
|
||||
Color.parse(value)
|
||||
except (ColorParseError, ValueError) as e:
|
||||
raise ValueError(f"{file}: {label}: {shorten(value)} is not a colour") from e
|
||||
return value
|
||||
|
||||
|
||||
def shorten(text: str, limit: int = 40) -> str:
|
||||
"""Quote a value from a theme file for an error message, cut to *limit* characters."""
|
||||
return repr(text if len(text) <= limit else text[:limit] + "...")
|
||||
|
||||
|
||||
def build_console_theme(palette: dict[str, str], styles: dict[str, str], set_terminal_bg: bool = False) -> Theme:
|
||||
"""Assemble the Rich console theme: fixed styles first, then the roles and the names made from them, then `styles:`."""
|
||||
on_bg = f" on {palette['bg']}" if set_terminal_bg else ""
|
||||
return Theme(
|
||||
{
|
||||
"bar.back": palette["dark_gray"],
|
||||
"bar.complete": palette["pink"],
|
||||
"bar.finished": palette["green"],
|
||||
"bar.pulse": palette["pink"],
|
||||
"inspect.async_def": f"italic {palette['cyan']}",
|
||||
"repr.number": f"bold not italic {palette['cyan']}",
|
||||
"repr.number_complex": f"bold not italic {palette['cyan']}",
|
||||
"rule.line": palette["dark_gray"],
|
||||
"rule.text": palette["pink"],
|
||||
"tree.line": palette["dark_gray"],
|
||||
"status.spinner": palette["pink"],
|
||||
"progress.spinner": palette["pink"],
|
||||
"ascii.art": palette["pink"] + on_bg,
|
||||
"none": palette["text"] + on_bg,
|
||||
"grey23": palette["black"],
|
||||
"magenta": palette["pink"],
|
||||
"bright_red": palette["red"],
|
||||
"bright_green": palette["green"],
|
||||
"bright_yellow": palette["yellow"],
|
||||
"bright_blue": palette["blue"],
|
||||
"bright_magenta": palette["pink"],
|
||||
"bright_cyan": palette["cyan"],
|
||||
**palette,
|
||||
**styles,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def build_help_config(palette: dict[str, str]) -> RichHelpConfiguration:
|
||||
"""Assemble the rich-click help configuration for a palette."""
|
||||
return RichHelpConfiguration(
|
||||
enable_theme_env_var=False,
|
||||
style_option=palette["text"],
|
||||
style_switch=palette["green"],
|
||||
style_argument=palette["cyan"],
|
||||
|
||||
Reference in New Issue
Block a user