portfetch 2.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
portfetch/stats.py ADDED
@@ -0,0 +1,117 @@
1
+ """Live values for placeholders: GitHub numbers and uptime."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as dt
6
+ import json
7
+ import os
8
+ import re
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ import urllib.error
13
+ import urllib.request
14
+
15
+ API = "https://api.github.com"
16
+
17
+
18
+ def github_token() -> str | None:
19
+ token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
20
+ if token:
21
+ return token
22
+ if shutil.which("gh"):
23
+ try:
24
+ out = subprocess.run(["gh", "auth", "token"], capture_output=True, text=True, timeout=5)
25
+ return out.stdout.strip() or None
26
+ except (OSError, subprocess.SubprocessError):
27
+ return None
28
+ return None
29
+
30
+
31
+ def gh_get(path: str, token: str | None):
32
+ req = urllib.request.Request(
33
+ f"{API}{path}",
34
+ headers={"Accept": "application/vnd.github+json", "User-Agent": "portfetch"},
35
+ )
36
+ if token:
37
+ req.add_header("Authorization", f"Bearer {token}")
38
+ with urllib.request.urlopen(req, timeout=20) as resp:
39
+ return json.load(resp)
40
+
41
+
42
+ def github_profile(user: str) -> dict:
43
+ return gh_get(f"/users/{user}", github_token())
44
+
45
+
46
+ def github_stats(user: str) -> dict[str, str]:
47
+ """Fetch public numbers for `user`. Missing values are left out, not faked."""
48
+ token = github_token()
49
+ stats: dict[str, str] = {}
50
+ try:
51
+ profile = gh_get(f"/users/{user}", token)
52
+ stats["followers"] = f"{profile.get('followers', 0):,}"
53
+ stats["following"] = f"{profile.get('following', 0):,}"
54
+ stats["gists"] = f"{profile.get('public_gists', 0):,}"
55
+ if profile.get("created_at"):
56
+ stats["joined"] = profile["created_at"][:4]
57
+
58
+ repos, page = [], 1
59
+ while True:
60
+ batch = gh_get(f"/users/{user}/repos?per_page=100&type=owner&page={page}", token)
61
+ repos += batch
62
+ if len(batch) < 100:
63
+ break
64
+ page += 1
65
+ own = [r for r in repos if not r.get("fork")]
66
+ stats["repos"] = f"{len(own):,}"
67
+ stats["stars"] = f"{sum(r.get('stargazers_count', 0) for r in own):,}"
68
+ stats["forks"] = f"{sum(r.get('forks_count', 0) for r in own):,}"
69
+
70
+ langs: dict[str, int] = {}
71
+ for r in own:
72
+ if r.get("language"):
73
+ langs[r["language"]] = langs.get(r["language"], 0) + 1
74
+ ranked = sorted(langs, key=langs.get, reverse=True)
75
+ stats["top_language"] = ranked[0] if ranked else ""
76
+ stats["top_languages"] = ", ".join(ranked[:3])
77
+
78
+ commits = gh_get(f"/search/commits?q=author:{user}&per_page=1", token)
79
+ stats["commits"] = f"{commits.get('total_count', 0):,}"
80
+ prs = gh_get(f"/search/issues?q=author:{user}+type:pr&per_page=1", token)
81
+ stats["prs"] = f"{prs.get('total_count', 0):,}"
82
+ except (urllib.error.URLError, TimeoutError, ValueError) as exc:
83
+ print(f"warning: some GitHub stats unavailable ({exc})", file=sys.stderr)
84
+ return stats
85
+
86
+
87
+ def offline_stats() -> dict[str, str]:
88
+ """Stand-in numbers so layouts can be previewed without network access."""
89
+ return {
90
+ "followers": "128", "following": "64", "gists": "4", "joined": "2020",
91
+ "repos": "42", "stars": "1,337", "forks": "99", "commits": "2,048", "prs": "256",
92
+ "top_language": "Python", "top_languages": "Python, R, TypeScript",
93
+ }
94
+
95
+
96
+ def uptime(since, today: dt.date | None = None) -> str:
97
+ start = since if isinstance(since, dt.date) else dt.date.fromisoformat(str(since))
98
+ today = today or dt.date.today()
99
+ years = today.year - start.year
100
+ months = today.month - start.month
101
+ days = today.day - start.day
102
+ if days < 0:
103
+ months -= 1
104
+ days += (today.replace(day=1) - dt.timedelta(days=1)).day
105
+ if months < 0:
106
+ years -= 1
107
+ months += 12
108
+ parts = []
109
+ for n, unit in ((years, "year"), (months, "month"), (days, "day")):
110
+ if n or (unit == "day" and not parts):
111
+ parts.append(f"{n} {unit}{'' if n == 1 else 's'}")
112
+ return ", ".join(parts)
113
+
114
+
115
+ def fill(text: str, values: dict[str, str]) -> str:
116
+ """Replace {name} with values[name]; unknown placeholders stay as written."""
117
+ return re.sub(r"\{(\w+)\}", lambda m: values.get(m.group(1), m.group(0)), text)
portfetch/svg.py ADDED
@@ -0,0 +1,435 @@
1
+ """Render the card as an SVG with optional CSS animation.
2
+
3
+ GitHub shows README images through <img>, which allows CSS animations but no
4
+ scripts and no web fonts. Two rules keep the card robust under those limits:
5
+
6
+ * Every element is fully visible in its resting style. Animations only hide
7
+ things while they run, so a viewer with `prefers-reduced-motion` sees the
8
+ finished card.
9
+ * Every line gets a fixed `textLength`, so columns stay aligned in whatever
10
+ monospace font the viewer has.
11
+
12
+ Animations are recorded on a Timeline as (from-state, to-state, start,
13
+ duration) events. A timeline is emitted either once (each element animates a
14
+ single time after a delay) or as a loop (each element gets keyframes placed
15
+ inside a repeating period). Loops let a card replay itself, and let the
16
+ showcase put several cards one after another in a single file.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import random
22
+ from dataclasses import dataclass, field
23
+ from xml.sax.saxutils import escape
24
+
25
+ from portfetch.art import CHAR_ASPECT
26
+ from portfetch.panel import Span
27
+
28
+ FONT_STACK = (
29
+ "ui-monospace, SFMono-Regular, Menlo, Consolas, "
30
+ "'Liberation Mono', 'DejaVu Sans Mono', monospace"
31
+ )
32
+
33
+ ANIMATIONS = {
34
+ "none": "a still card",
35
+ "fade": "the portrait fades in, then the info lines rise in one after another",
36
+ "boot": "the portrait draws row by row, then the info prints line by line, like a boot log",
37
+ "typewriter": "the portrait fades in while every info line types itself out",
38
+ "scan": "a scanline sweeps down and reveals the portrait, then the info fades in",
39
+ "decode": "the portrait flickers through random characters before it resolves",
40
+ }
41
+
42
+ WINDOWS = {
43
+ "card": "rounded card with a thin border (default)",
44
+ "macos": "terminal window with traffic lights and a title bar",
45
+ "none": "no frame or background, for a transparent look",
46
+ }
47
+
48
+ TITLEBAR = 30
49
+ SCRAMBLE = "!<>-_\\/[]{}=+*^?#%&$@01"
50
+ HIDDEN = "opacity:0"
51
+ SHOWN = "opacity:1"
52
+
53
+
54
+ @dataclass
55
+ class Layout:
56
+ width: int = 60
57
+ font_size: float = 14
58
+ line_height: float = 20
59
+ padding: float = 28
60
+ gap: float = 28
61
+ art_font_size: float | None = None
62
+ window: str = "card"
63
+ title: str = ""
64
+
65
+
66
+ @dataclass
67
+ class Animation:
68
+ style: str = "none"
69
+ duration: float = 2.5
70
+ delay: float = 0.2
71
+ cursor: bool = False
72
+ prompt: str = "~ $"
73
+ loop: float | None = None # seconds to hold the finished card before replaying
74
+ seed: int = 7
75
+
76
+ @classmethod
77
+ def from_config(cls, spec) -> "Animation":
78
+ if spec is None or spec is False:
79
+ return cls()
80
+ if isinstance(spec, str):
81
+ spec = {"style": spec}
82
+ anim = cls(**{k: v for k, v in spec.items() if k in cls.__dataclass_fields__})
83
+ if anim.style not in ANIMATIONS:
84
+ raise ValueError(f"unknown animation '{anim.style}'. Choose from: {', '.join(ANIMATIONS)}")
85
+ if anim.loop is True:
86
+ anim.loop = 4.0
87
+ return anim
88
+
89
+
90
+ # ---------------------------------------------------------------------------
91
+ # Timeline
92
+ # ---------------------------------------------------------------------------
93
+
94
+ @dataclass
95
+ class _Event:
96
+ frm: str
97
+ to: str
98
+ start: float
99
+ dur: float
100
+ timing: str
101
+
102
+
103
+ class Timeline:
104
+ """Collects animation events and turns them into CSS."""
105
+
106
+ def __init__(self, prefix: str):
107
+ self.prefix = prefix
108
+ self.events: list[_Event] = []
109
+
110
+ def attr(self, frm: str, to: str, start: float, dur: float, timing: str = "linear") -> str:
111
+ """Return a placeholder style attribute, filled in by `finish`."""
112
+ self.events.append(_Event(frm, to, max(0.0, start), max(0.01, dur), timing))
113
+ return f' style="@@{self.prefix}{len(self.events) - 1}@@"'
114
+
115
+ @property
116
+ def end(self) -> float:
117
+ return max((e.start + e.dur for e in self.events), default=0.0)
118
+
119
+ def finish(self, body: str, loop: tuple[float, float] | None = None,
120
+ reset: float | None = None) -> tuple[str, list[str]]:
121
+ """Fill the placeholders.
122
+
123
+ `loop` is (offset, period) in seconds, or None to play once. In a loop,
124
+ `reset` is a time after which every element snaps back to its starting
125
+ state, so a scene can sit ready, unplayed, before its next turn.
126
+ """
127
+ css: list[str] = []
128
+ shared: dict[tuple[str, str], str] = {}
129
+ for i, e in enumerate(self.events):
130
+ token = f"@@{self.prefix}{i}@@"
131
+ if loop is None:
132
+ name = shared.get((e.frm, e.to))
133
+ if name is None:
134
+ name = shared[(e.frm, e.to)] = f"{self.prefix}k{len(shared)}"
135
+ css.append(f"@keyframes {name}{{from{{{e.frm}}}to{{{e.to}}}}}")
136
+ style = f"animation:{name} {e.dur:.3f}s {e.timing} {e.start:.3f}s both"
137
+ else:
138
+ offset, period = loop
139
+ a = min(100.0, (offset + e.start) / period * 100)
140
+ b = min(100.0, (offset + e.start + e.dur) / period * 100)
141
+ name = f"{self.prefix}e{i}"
142
+ tail = f"{b:.3f}%,100%{{{e.to}}}"
143
+ if reset is not None and reset / period * 100 > b:
144
+ r = reset / period * 100
145
+ tail = f"{b:.3f}%,{r:.3f}%{{{e.to}}}{min(100.0, r + 0.001):.3f}%,100%{{{e.frm}}}"
146
+ css.append(
147
+ f"@keyframes {name}{{0%,{a:.3f}%{{{e.frm};animation-timing-function:{e.timing}}}{tail}}}"
148
+ )
149
+ style = f"animation:{name} {period:.3f}s linear infinite"
150
+ body = body.replace(token, style)
151
+ return body, css
152
+
153
+
154
+ # ---------------------------------------------------------------------------
155
+ # Card
156
+ # ---------------------------------------------------------------------------
157
+
158
+ @dataclass
159
+ class Parts:
160
+ width: float
161
+ height: float
162
+ css: list[str] = field(default_factory=list)
163
+ body: str = ""
164
+ timeline: Timeline | None = None
165
+
166
+
167
+ def render(art: list[str], rows: list[list[Span]], theme: dict, layout: Layout,
168
+ anim: Animation | None = None, header: str = "") -> str:
169
+ """Render one card as a complete SVG document."""
170
+ anim = anim or Animation()
171
+ parts = render_parts(art, rows, theme, layout, anim, header, prefix="pf-")
172
+ loop = (0.0, parts.timeline.end + anim.loop) if anim.loop and anim.style != "none" else None
173
+ body, css = parts.timeline.finish(parts.body, loop)
174
+ return assemble(parts.width, parts.height, parts.css + css, body)
175
+
176
+
177
+ def render_parts(art: list[str], rows: list[list[Span]], theme: dict, layout: Layout,
178
+ anim: Animation, header: str, prefix: str) -> Parts:
179
+ """Lay out one card. Its animations stay on the returned timeline until finished."""
180
+ p = prefix
181
+ tl = Timeline(p)
182
+ font, lh, pad = layout.font_size, layout.line_height, layout.padding
183
+ cw = font * CHAR_ASPECT
184
+
185
+ n_rows = len(rows) + (2 if anim.cursor else 0) # blank spacer + prompt line
186
+ info_h = n_rows * lh
187
+ info_w = layout.width * cw
188
+
189
+ if art:
190
+ art_font = layout.art_font_size or min(font, info_h / len(art))
191
+ art_w = len(art[0]) * art_font * CHAR_ASPECT
192
+ art_h = len(art) * art_font
193
+ else:
194
+ art_font = art_w = art_h = 0.0
195
+
196
+ top = TITLEBAR if layout.window == "macos" else 0
197
+ body_h = max(info_h, art_h)
198
+ total_w = pad * 2 + art_w + (layout.gap if art else 0) + info_w
199
+ total_h = top + pad * 2 + body_h
200
+ art_x, art_y = pad, top + pad + (body_h - art_h) / 2
201
+ info_x = pad + art_w + (layout.gap if art else 0)
202
+ info_y = top + pad + (body_h - info_h) / 2
203
+
204
+ css = [
205
+ f".{p}art{{fill:{theme['art']};font-size:{art_font:.2f}px}}",
206
+ f".{p}info{{font-size:{font}px}}",
207
+ *(f".{p}{role}{{fill:{theme[role]}}}" for role in ("header", "key", "value", "dots", "section")),
208
+ f".{p}noise,.{p}scanline{{opacity:0}}",
209
+ f".{p}cover{{transform-box:fill-box;transform-origin:right center}}",
210
+ f".{p}blink{{animation:{p}blink 1.1s steps(1) infinite}}",
211
+ f"@keyframes {p}blink{{50%{{opacity:0}}}}",
212
+ "@media (prefers-reduced-motion:reduce){"
213
+ f".{p}cover,.{p}noise,.{p}scanline{{display:none}}}}",
214
+ ]
215
+ body: list[str] = []
216
+ _frame(body, theme, layout, total_w, total_h, header)
217
+
218
+ style = anim.style
219
+ moving = style != "none"
220
+ t0, dur = anim.delay, max(0.5, anim.duration)
221
+ art_time = dur * 0.45 if style in ("boot", "scan", "decode") else 0.0
222
+ info_start = t0 + (art_time if art_time else 0.25)
223
+ info_span = dur - art_time
224
+
225
+ def show(at: float) -> str:
226
+ return tl.attr(HIDDEN, SHOWN, at, 0.01) if moving else ""
227
+
228
+ # ---- art -------------------------------------------------------------
229
+ rng = random.Random(anim.seed)
230
+ if art:
231
+ group = tl.attr(HIDDEN, SHOWN, t0, 0.9, "ease-out") if style in ("fade", "typewriter") else ""
232
+ body.append(f"<g{group}>")
233
+ for i, line in enumerate(art):
234
+ y = art_y + (i + 0.8) * art_font
235
+ attrs = (f'x="{art_x:.2f}" y="{y:.2f}" textLength="{art_w:.2f}" '
236
+ f'lengthAdjust="spacing" xml:space="preserve"')
237
+ row_at = t0 + art_time * i / len(art)
238
+ if style in ("boot", "scan"):
239
+ body.append(f'<text class="{p}art"{show(row_at)} {attrs}>{escape(line)}</text>')
240
+ elif style == "decode":
241
+ settle = row_at + 0.35 + rng.random() * 0.5
242
+ noise = "".join(c if c == " " else rng.choice(SCRAMBLE) for c in line)
243
+ hide = tl.attr(SHOWN, HIDDEN, settle, 0.01)
244
+ body.append(f'<text class="{p}art {p}noise"{hide} {attrs}>{escape(noise)}</text>')
245
+ body.append(f'<text class="{p}art"{show(settle)} {attrs}>{escape(line)}</text>')
246
+ else:
247
+ body.append(f'<text class="{p}art" {attrs}>{escape(line)}</text>')
248
+ body.append("</g>")
249
+ if style == "scan":
250
+ sweep = tl.attr("opacity:1;transform:translateY(0)",
251
+ f"opacity:0;transform:translateY({art_h:.1f}px)", t0, art_time)
252
+ body.append(
253
+ f'<rect class="{p}scanline"{sweep} x="{art_x - 6:.1f}" y="{art_y:.1f}" '
254
+ f'width="{art_w + 12:.1f}" height="2" fill="{theme["cursor"]}"/>'
255
+ )
256
+
257
+ # ---- info ------------------------------------------------------------
258
+ n = len(rows)
259
+ step = info_span / max(n, 1) * (0.6 if style == "typewriter" else 1.0)
260
+ last = info_start
261
+ for i, spans in enumerate(rows):
262
+ y = info_y + (i + 0.75) * lh
263
+ chars = sum(len(s) for _, s in spans)
264
+ inner = "".join(f'<tspan class="{p}{role}">{escape(s)}</tspan>' for role, s in spans)
265
+ attrs = (f'x="{info_x:.2f}" y="{y:.2f}" textLength="{chars * cw:.2f}" '
266
+ f'lengthAdjust="spacing" xml:space="preserve"')
267
+ at = info_start + i * step
268
+ if style == "fade":
269
+ effect = tl.attr("opacity:0;transform:translateY(6px)", "opacity:1;transform:none", at, 0.5, "ease-out")
270
+ elif style == "boot":
271
+ effect = show(at)
272
+ elif style in ("scan", "decode"):
273
+ effect = tl.attr(HIDDEN, SHOWN, at, 0.6, "ease-out")
274
+ else:
275
+ effect = ""
276
+ body.append(f'<text class="{p}info"{effect} {attrs}>{inner}</text>')
277
+ last = at + 0.5
278
+ if style == "typewriter":
279
+ typed = max(1, len("".join(s for _, s in spans).rstrip()))
280
+ secs = max(0.2, typed / 70)
281
+ wipe = tl.attr("transform:scaleX(1)", "transform:scaleX(0)", at, secs, f"steps({typed},end)")
282
+ body.append(
283
+ f'<rect class="{p}cover"{wipe} x="{info_x - 1:.2f}" y="{y - 0.75 * lh:.2f}" '
284
+ f'width="{chars * cw + 2:.2f}" height="{lh:.2f}" fill="{theme["background"]}"/>'
285
+ )
286
+ last = at + secs
287
+
288
+ # ---- cursor ----------------------------------------------------------
289
+ if anim.cursor:
290
+ y = info_y + (n + 1 + 0.75) * lh
291
+ prompt = f"{header} {anim.prompt} " if header else f"{anim.prompt} "
292
+ body.append(
293
+ f'<g{show(last)}><text class="{p}info {p}dots" x="{info_x:.2f}" y="{y:.2f}" '
294
+ f'textLength="{len(prompt) * cw:.2f}" lengthAdjust="spacing" xml:space="preserve">'
295
+ f'{escape(prompt)}</text>'
296
+ f'<rect class="{p}blink" x="{info_x + len(prompt) * cw:.2f}" y="{y - 0.8 * font:.2f}" '
297
+ f'width="{cw:.2f}" height="{font:.2f}" fill="{theme["cursor"]}"/></g>'
298
+ )
299
+
300
+ return Parts(total_w, total_h, css, "\n".join(body), tl)
301
+
302
+
303
+ def _frame(body: list[str], theme: dict, layout: Layout, w: float, h: float, header: str) -> None:
304
+ if layout.window == "none":
305
+ return
306
+ body.append(
307
+ f'<rect x="0.5" y="0.5" width="{w - 1:.1f}" height="{h - 1:.1f}" rx="12" '
308
+ f'fill="{theme["background"]}" stroke="{theme["border"]}"/>'
309
+ )
310
+ if layout.window == "macos":
311
+ body.append(
312
+ f'<path d="M0.5,{TITLEBAR} V12.5 A12,12 0 0 1 12.5,0.5 H{w - 12.5:.1f} '
313
+ f'A12,12 0 0 1 {w - 0.5:.1f},12.5 V{TITLEBAR} Z" fill="{theme["titlebar"]}" stroke="{theme["border"]}"/>'
314
+ )
315
+ for k, color in enumerate(("#ff5f57", "#febc2e", "#28c840")):
316
+ body.append(f'<circle cx="{20 + k * 20}" cy="{TITLEBAR / 2}" r="6" fill="{color}"/>')
317
+ title = layout.title or (f"{header}: ~" if header else "portfetch")
318
+ body.append(
319
+ f'<text x="{w / 2:.1f}" y="{TITLEBAR / 2 + 4.5:.1f}" text-anchor="middle" '
320
+ f'style="font-size:12.5px" fill="{theme["dots"]}">{escape(title)}</text>'
321
+ )
322
+
323
+
324
+ def assemble(w: float, h: float, css: list[str], body: str) -> str:
325
+ head = (
326
+ f'<svg xmlns="http://www.w3.org/2000/svg" width="{w:.0f}" height="{h:.0f}" '
327
+ f'viewBox="0 0 {w:.1f} {h:.1f}" font-family="{FONT_STACK}">'
328
+ )
329
+ css = [*css, "text{white-space:pre}",
330
+ "@media (prefers-reduced-motion:reduce){*{animation:none!important}}"]
331
+ return "\n".join([head, "<style>", *css, "</style>", body, "</svg>"]) + "\n"
332
+
333
+
334
+ # ---------------------------------------------------------------------------
335
+ # Showcase: several cards that take turns in one looping SVG
336
+ # ---------------------------------------------------------------------------
337
+
338
+ @dataclass
339
+ class Scene:
340
+ art: list[str]
341
+ rows: list[list[Span]]
342
+ theme: dict
343
+ layout: Layout
344
+ anim: Animation
345
+ header: str
346
+ caption: str = ""
347
+
348
+
349
+ def _opacity_keyframes(name: str, points: list[tuple[float, float]], period: float) -> str:
350
+ """Keyframes through (time, opacity) points, easing in and out between them."""
351
+ points = sorted(points)
352
+ if points[0][0] > 0:
353
+ points.insert(0, (0.0, points[0][1]))
354
+ if points[-1][0] < period:
355
+ points.append((period, points[-1][1]))
356
+ frames = "".join(
357
+ f"{min(100.0, t / period * 100):.3f}%{{opacity:{v:g};animation-timing-function:ease-in-out}}"
358
+ for t, v in points
359
+ )
360
+ return f"@keyframes {name}{{{frames}}}"
361
+
362
+
363
+ def showcase(scenes: list[Scene], hold: float = 2.5, fade: float = 0.9,
364
+ caption_color: str = "#8b949e") -> str:
365
+ """Play each scene's intro, hold it, cross-fade to the next, and loop forever.
366
+
367
+ The incoming scene fades in on top of the outgoing one, which stays
368
+ mostly opaque underneath, so the canvas never flashes empty. On the wrap
369
+ from the last scene back to the first, the last one fades out instead,
370
+ over the first scene, which has already been reset to its empty frame.
371
+ """
372
+ caption_h = 34 if any(s.caption for s in scenes) else 0
373
+ built = [render_parts(sc.art, sc.rows, sc.theme, sc.layout, sc.anim, sc.header, prefix=f"s{k}-")
374
+ for k, sc in enumerate(scenes)]
375
+
376
+ # Scene k starts at starts[k] and begins handing over at ends[k].
377
+ starts, ends, t = [], [], 0.0
378
+ for parts in built:
379
+ starts.append(t)
380
+ t += parts.timeline.end + hold
381
+ ends.append(t)
382
+ period = ends[-1] + fade
383
+ n = len(scenes)
384
+
385
+ width = max(parts.width for parts in built)
386
+ height = max(parts.height for parts in built) + caption_h
387
+
388
+ css: list[str] = []
389
+ body: list[str] = []
390
+ for k, (scene, parts) in enumerate(zip(scenes, built)):
391
+ reset = (ends[-1] - 0.01) if k == 0 and n > 1 else None
392
+ scene_body, scene_css = parts.timeline.finish(parts.body, (starts[k], period), reset)
393
+ css += parts.css + scene_css
394
+
395
+ if n == 1:
396
+ points = [(0.0, 1.0)]
397
+ elif k == 0:
398
+ points = [(0.0, 1.0), (ends[0] + 0.4 * fade, 1.0), (ends[0] + fade, 0.0),
399
+ (ends[-1] - 0.001, 0.0), (ends[-1], 1.0)]
400
+ elif k == n - 1:
401
+ points = [(0.0, 0.0), (starts[k], 0.0), (starts[k] + fade, 1.0), (ends[k], 1.0), (period, 0.0)]
402
+ else:
403
+ points = [(0.0, 0.0), (starts[k], 0.0), (starts[k] + fade, 1.0),
404
+ (ends[k] + 0.4 * fade, 1.0), (ends[k] + fade, 0.0)]
405
+ css.append(_opacity_keyframes(f"s{k}-scene", points, period))
406
+
407
+ resting = "" if k == 0 else "opacity:0;"
408
+ x = (width - parts.width) / 2
409
+ y = (height - caption_h - parts.height) / 2
410
+ body.append(f'<g style="{resting}animation:s{k}-scene {period:.3f}s linear infinite">'
411
+ f'<g transform="translate({x:.1f},{y:.1f})">{scene_body}</g></g>')
412
+
413
+ # Captions dip out and back in, so two never overlap.
414
+ half = fade / 2
415
+ for k, scene in enumerate(scenes):
416
+ if not scene.caption:
417
+ continue
418
+ if n == 1:
419
+ points = [(0.0, 1.0)]
420
+ elif k == 0:
421
+ points = [(0.0, 1.0), (ends[0], 1.0), (ends[0] + half, 0.0),
422
+ (period - half, 0.0), (period, 1.0)]
423
+ else:
424
+ out_at = ends[k]
425
+ points = [(0.0, 0.0), (starts[k] + half, 0.0), (starts[k] + fade, 1.0),
426
+ (out_at, 1.0), (out_at + half, 0.0)]
427
+ css.append(_opacity_keyframes(f"s{k}-caption", points, period))
428
+ resting = "" if k == 0 else "opacity:0;"
429
+ body.append(
430
+ f'<text x="{width / 2:.1f}" y="{height - 10:.1f}" text-anchor="middle" xml:space="preserve" '
431
+ f'style="{resting}font-size:13px;animation:s{k}-caption {period:.3f}s linear infinite" '
432
+ f'fill="{caption_color}">{escape(scene.caption)}</text>'
433
+ )
434
+
435
+ return assemble(width, height, css, "\n".join(body))
portfetch/themes.py ADDED
@@ -0,0 +1,88 @@
1
+ """Color themes. Each theme sets every color role the card uses."""
2
+
3
+ from __future__ import annotations
4
+
5
+ ROLES = ("background", "border", "titlebar", "art", "header", "key", "value", "dots", "section", "cursor")
6
+
7
+ THEMES: dict[str, dict[str, str]] = {
8
+ "github-light": {
9
+ "background": "#f6f8fa", "border": "#d0d7de", "titlebar": "#eaeef2", "art": "#57606a",
10
+ "header": "#24292f", "key": "#953800", "value": "#0a3069", "dots": "#8c959f",
11
+ "section": "#24292f", "cursor": "#0969da",
12
+ },
13
+ "github-dark": {
14
+ "background": "#161b22", "border": "#30363d", "titlebar": "#21262d", "art": "#c9d1d9",
15
+ "header": "#e6edf3", "key": "#ffa657", "value": "#a5d6ff", "dots": "#6e7681",
16
+ "section": "#e6edf3", "cursor": "#58a6ff",
17
+ },
18
+ "dracula": {
19
+ "background": "#282a36", "border": "#44475a", "titlebar": "#21222c", "art": "#f8f8f2",
20
+ "header": "#50fa7b", "key": "#ff79c6", "value": "#8be9fd", "dots": "#6272a4",
21
+ "section": "#bd93f9", "cursor": "#f8f8f2",
22
+ },
23
+ "nord": {
24
+ "background": "#2e3440", "border": "#3b4252", "titlebar": "#3b4252", "art": "#d8dee9",
25
+ "header": "#88c0d0", "key": "#81a1c1", "value": "#a3be8c", "dots": "#4c566a",
26
+ "section": "#ebcb8b", "cursor": "#88c0d0",
27
+ },
28
+ "tokyo-night": {
29
+ "background": "#1a1b26", "border": "#292e42", "titlebar": "#16161e", "art": "#a9b1d6",
30
+ "header": "#7aa2f7", "key": "#bb9af7", "value": "#9ece6a", "dots": "#565f89",
31
+ "section": "#e0af68", "cursor": "#c0caf5",
32
+ },
33
+ "catppuccin-mocha": {
34
+ "background": "#1e1e2e", "border": "#313244", "titlebar": "#181825", "art": "#cdd6f4",
35
+ "header": "#89b4fa", "key": "#f5c2e7", "value": "#a6e3a1", "dots": "#6c7086",
36
+ "section": "#fab387", "cursor": "#f5e0dc",
37
+ },
38
+ "catppuccin-latte": {
39
+ "background": "#eff1f5", "border": "#ccd0da", "titlebar": "#e6e9ef", "art": "#5c5f77",
40
+ "header": "#1e66f5", "key": "#8839ef", "value": "#40a02b", "dots": "#9ca0b0",
41
+ "section": "#fe640b", "cursor": "#dc8a78",
42
+ },
43
+ "gruvbox-dark": {
44
+ "background": "#282828", "border": "#3c3836", "titlebar": "#1d2021", "art": "#ebdbb2",
45
+ "header": "#b8bb26", "key": "#fe8019", "value": "#83a598", "dots": "#665c54",
46
+ "section": "#fabd2f", "cursor": "#ebdbb2",
47
+ },
48
+ "gruvbox-light": {
49
+ "background": "#fbf1c7", "border": "#d5c4a1", "titlebar": "#ebdbb2", "art": "#504945",
50
+ "header": "#79740e", "key": "#af3a03", "value": "#076678", "dots": "#a89984",
51
+ "section": "#b57614", "cursor": "#3c3836",
52
+ },
53
+ "solarized-dark": {
54
+ "background": "#002b36", "border": "#073642", "titlebar": "#073642", "art": "#93a1a1",
55
+ "header": "#268bd2", "key": "#cb4b16", "value": "#2aa198", "dots": "#586e75",
56
+ "section": "#b58900", "cursor": "#93a1a1",
57
+ },
58
+ "solarized-light": {
59
+ "background": "#fdf6e3", "border": "#eee8d5", "titlebar": "#eee8d5", "art": "#586e75",
60
+ "header": "#268bd2", "key": "#cb4b16", "value": "#2aa198", "dots": "#93a1a1",
61
+ "section": "#b58900", "cursor": "#586e75",
62
+ },
63
+ "green-screen": {
64
+ "background": "#0a0f0a", "border": "#1f3a1f", "titlebar": "#102010", "art": "#33ff66",
65
+ "header": "#66ff99", "key": "#33ff66", "value": "#b3ffc6", "dots": "#1f7a3a",
66
+ "section": "#66ff99", "cursor": "#33ff66",
67
+ },
68
+ }
69
+
70
+ # Output names map to these presets unless the config says otherwise.
71
+ DEFAULT_FOR_OUTPUT = {"light": "github-light", "dark": "github-dark"}
72
+
73
+
74
+ def resolve(spec, output_name: str) -> dict[str, str]:
75
+ """Build a full palette from a preset name or {preset: name, role: color, ...}."""
76
+ preset = DEFAULT_FOR_OUTPUT.get(output_name, "github-dark")
77
+ overrides: dict = {}
78
+ if isinstance(spec, str):
79
+ preset = spec
80
+ elif isinstance(spec, dict):
81
+ preset = spec.get("preset", preset)
82
+ overrides = {k: v for k, v in spec.items() if k != "preset"}
83
+ if preset not in THEMES:
84
+ raise ValueError(f"unknown theme '{preset}'. Run `portfetch themes` to list them.")
85
+ unknown = set(overrides) - set(ROLES)
86
+ if unknown:
87
+ raise ValueError(f"unknown theme colors: {', '.join(sorted(unknown))}. Valid: {', '.join(ROLES)}")
88
+ return {**THEMES[preset], **overrides}