caelestia-niri/assets/dots/fastfetch/fetch.py

162 lines
6 KiB
Python

#!/usr/bin/env python3
"""Window-width-aware system summary in the style of astra-dots' fastfetch config.
Reads its data from fastfetch (JSON), draws the Keys/Values/Colors boxes to fit the
terminal: the logo is dropped when it would not fit, values are clipped with an ellipsis,
and the boxes shrink to the window.
"""
import json, os, re, shutil, subprocess
from datetime import datetime
R = "\033[0m"; G = "\033[90m"
ANSI = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
vis = lambda s: len(ANSI.sub("", s))
def pad(s, w):
return s + " " * max(0, w - vis(s))
def clip(s, w):
"""Cut s (which may hold colour codes) to w visible columns, adding an ellipsis."""
if vis(s) <= w:
return s
out, n, i = "", 0, 0
while i < len(s) and n < w - 1:
m = ANSI.match(s, i)
if m:
out += m.group(); i = m.end(); continue
out += s[i]; n += 1; i += 1
return out + "…" + R
def ff(*mods):
out = subprocess.run(["fastfetch", "-c", "none", "--format", "json", "-s", ":".join(mods)], capture_output=True, text=True).stdout
return {d["type"]: d["result"] for d in json.loads(out)}
def gib(b):
return f"{b / 1024**3:.2f} GiB"
def br(txt, col=""):
return f" {G}[{R}{col}{txt}{R}{G}]{R}"
def pct(p):
c = "92" if p < 60 else "93" if p < 85 else "91"
return f"\033[{c}m{p}%"
d = ff("Host", "OS", "Kernel", "WM", "Terminal", "Shell", "CPU", "GPU", "Memory", "Disk")
user = os.environ.get("USER", "")
shell = os.path.basename(os.environ.get("SHELL", "sh"))
try:
shell_v = re.search(r"\d+(\.\d+)+", subprocess.run([os.environ.get("SHELL", "sh"), "--version"], capture_output=True, text=True).stdout).group()
except Exception:
shell_v = ""
term = "kitty" if os.environ.get("KITTY_WINDOW_ID") else d["Terminal"]["prettyName"]
term_v = os.environ.get("KITTY_PID") and subprocess.run(["kitty", "--version"], capture_output=True, text=True).stdout.split()[1] or ""
cpu_temp = ""
for hw in ("/sys/class/hwmon",):
try:
for h in os.listdir(hw):
if open(f"{hw}/{h}/name").read().strip() == "coretemp":
cpu_temp = f"{int(open(f'{hw}/{h}/temp1_input').read()) / 1000:.1f}°C"
break
except Exception:
pass
mem = d["Memory"]
rows = [
("User", "92", f"\033[92m{user}@{os.uname().nodename}{R}"),
("OS", "94", d["OS"]["prettyName"]),
("Host", "94", f"{d['Host']['vendor'].replace(' Inc.', '')} {d['Host']['name']}" + br(d["Host"]["version"])),
("Kernel", "94", d["Kernel"]["name"] + br("v" + d["Kernel"]["release"])),
("WM", "96", f"{d['WM']['prettyName']}" + br(d["WM"]["version"])),
("Terminal", "96", term + (br("v" + term_v) if term_v else "")),
("Shell", "96", shell + (br("v" + shell_v) if shell_v else "")),
("CPU", "93", d["CPU"]["cpu"].replace("(R)", "").replace("(TM)", "").replace(" ", " ") + (br(cpu_temp, "\033[93m") if cpu_temp else "") + br(f"{d['CPU']['frequency']['max'] / 1000:.2f} GHz")),
("GPU", "93", d["GPU"][0]["name"]),
("Memory", "93", f"{gib(mem['used'])} / {gib(mem['total'])}" + br(pct(mem['used'] * 100 // mem['total']))),
]
for x in d["Disk"]:
if x["mountpoint"] == "/" or x["mountpoint"].startswith("/mnt"):
t, f = x["bytes"]["total"], x["bytes"]["free"]
rows.append(("Disk", "93", f"{gib(t - f)} / {gib(t)}" + br(pct((t - f) * 100 // t))))
now = datetime.now()
rows.append(("Datetime", "97", now.strftime("%d-%m-%Y %I:%M:%S %p") + br(now.strftime("%A"), "\033[96m")))
cols = shutil.get_terminal_size((100, 30)).columns
logo = [l.rstrip("\n") for l in open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "arch-logo.ans"))]
logo = [l for l in logo if l.strip()]
logo_w = max(vis(l) for l in logo)
kw = max(len(k) for k, _, _ in rows) # key text width
box_key_w = kw + 4 # "│ " + text + " │"
want_val = max(vis(v) for _, _, v in rows) + 4
want_vals_w = max(want_val, 40)
gap = 1
def layout(with_logo):
avail = cols - 1 - ((logo_w + 3) if with_logo else 0)
vals_w = min(want_vals_w, avail - box_key_w - gap)
return avail, vals_w
with_logo = True
avail, vals_w = layout(True)
if vals_w < min(want_vals_w, 44): # logo would squeeze the panels: drop it
with_logo = False
avail, vals_w = layout(False)
two = vals_w >= 14 # enough room for Keys and Values side by side
total_w = (box_key_w + gap + vals_w) if two else max(10, avail)
def top(title, w):
return f"{G}╭ {title} " + "─" * max(0, w - len(title) - 4) + f"╮{R}"
def bottom(w):
return f"{G}╰" + "─" * (w - 2) + f"╯{R}"
def row(content, w, color=""):
return f"{G}│{R} " + pad(clip(content, w - 4), w - 4) + f" {G}│{R}"
lines = []
if two:
keys = [top("Keys", box_key_w)] + [row(f"\033[{c}m{k}{R}", box_key_w) for k, c, _ in rows] + [bottom(box_key_w)]
vals = [top("Values", vals_w)] + [row(v, vals_w) for _, _, v in rows] + [bottom(vals_w)]
lines += [a + " " * gap + b for a, b in zip(keys, vals)]
else:
lines += [top("Info", total_w)] + [row(f"\033[{c}m{k}{R} {v}", total_w) for k, c, v in rows] + [bottom(total_w)]
lines.append("")
cw = min(total_w, 8 * 4 + 4)
if cw >= 12 and total_w >= 12:
cw = min(total_w, max(cw, 12))
n = max(1, (cw - 4) // 4)
s1 = "".join(f"\033[4{i}m {R}" for i in range(min(8, n)))
s2 = "".join(f"\033[10{i}m {R}" for i in range(min(8, n)))
lines += [top("Colors", total_w), f"{G}│{R} " + pad(s1, total_w - 4) + f" {G}│{R}",
f"{G}│{R} " + pad(s2, total_w - 4) + f" {G}│{R}", bottom(total_w)]
hour = now.hour
word = __import__("random").choice(["Hello", "Hey", "Hi", "Greetings", "Welcome", "Good morning" if hour < 12 else "Good afternoon" if hour < 17 else "Good evening"])
hello = f" \033[97m{word},{R} \033[1;36m{user.capitalize()}{R}!"
print()
if with_logo:
print(" " * (logo_w + 3) + hello)
print()
for i in range(max(len(logo), len(lines))):
l = logo[i] + R if i < len(logo) else ""
r = lines[i] if i < len(lines) else ""
print(pad(l, logo_w) + " " + r)
else:
print(hello)
print()
for l in lines:
print(l)
print()