"""The widgets the main screen is built from: file tables, the detail pane, the run panel and the log viewer.""" import os import time from rich.console import Group from rich.table import Table from rich.text import Text from textual.containers import Horizontal, Vertical from textual.widgets import DataTable, Label, RichLog, Select, Static from ..common import ME, fmt_ago, fmt_clock, fmt_dur # Semantic colours for cell content (rich styles). Chrome colours come from the theme via styles.tcss. GOOD, BAD, WARN, HOT, ACCENT, DIM = "#9ece6a", "#f7768e", "#e0af68", "#bb9af7", "#7aa2f7", "#737aa2" INK = "#1a1b26" # text on coloured pills SPIN = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏" def spinner(): return SPIN[int(time.time() * 10) % len(SPIN)] def pill(text, colour): return Text(" %s " % text, style="bold %s on %s" % (INK, colour)) def join(parts, sep=" "): out = Text() for i, part in enumerate(parts): if i: out.append(sep) out.append_text(part) return out # -- file tables --------------------------------------------------------------- def mark_cell(on): return Text("●", style="bold " + ACCENT) if on else Text("○", style=DIM) def holder_cell(holder, free_label="—"): if not holder: return Text(free_label, style=GOOD if free_label == "free" else DIM) if holder == ME: return Text("you", style="bold " + GOOD) return Text(holder, style="bold " + BAD) def version_cell(r): if r["kind"] == "A": return Text("new file", style=DIM) if r["unknown"]: return Text("%s → %s" % (r["base"] or "?", r["latest"] or "?"), style=WARN) if r["stale"]: return Text("%s → %s" % (r["base"], r["latest"]), style="bold " + BAD) return Text.assemble((r["base"], ""), (" latest", DIM)) def flags_cell(r, in_run): flags = [] if r.get("hot"): flags.append(pill("HOT", HOT)) if r.get("stale"): flags.append(pill("STALE", BAD)) if r.get("unknown") and r.get("kind") == "M": flags.append(pill("?VER", WARN)) if r.get("exists") is False: flags.append(pill("MISSING", BAD)) if in_run: flags.append(pill("IN-RUN", ACCENT)) return join(flags) def local_cell(r): return Text("modified", style=WARN) if r["modified"] else Text("clean", style=DIM) class FileTable(DataTable): """A row-cursor table of file rows that remembers the cursor by path across refreshes.""" COLUMNS = { "changes": [("", "mark", 1), ("St", "st", 2), ("File", "file", None), ("Base → Latest", "ver", 14), ("Lock", "lock", 10), ("Flags", "flags", None)], "locks": [("", "mark", 1), ("File", "file", None), ("Holder", "holder", 12), ("Local copy", "local", 10), ("Flags", "flags", None)], "checkout": [("", "mark", 1), ("File", "file", None), ("Local copy", "local", 10), ("Flags", "flags", None)], } def __init__(self, kind): super().__init__(cursor_type="row", zebra_stripes=True, id="table-" + kind) self.kind = kind self.file_rows = [] self.click_column = None # set while a mouse click is being handled async def _on_click(self, event): # a click on the ● column toggles the mark; anywhere else it only moves the cursor self.click_column = event.style.meta.get("column") try: await super()._on_click(event) finally: self.click_column = None def selection_toggles(self): return self.click_column is None or self.click_column == 0 def on_mount(self): for label, key, width in self.COLUMNS[self.kind]: self.add_column(label, key=key, width=width) def current(self): if 0 <= self.cursor_row < len(self.file_rows): return self.file_rows[self.cursor_row] return None def show(self, rows, marks, run_files, text_filter): keep = self.current() needle = text_filter.lower() self.file_rows = [r for r in rows if needle in r["path"].lower()] self.clear() for r in self.file_rows: self.add_row(*self.cells(r, marks, run_files), key=r["path"]) if keep: index = next((i for i, r in enumerate(self.file_rows) if r["path"] == keep["path"]), 0) self.move_cursor(row=index, animate=False) def refresh_marks(self, marks): for r in self.file_rows: self.update_cell(r["path"], "mark", mark_cell(r["path"] in marks)) def cells(self, r, marks, run_files): mark, path, in_run = mark_cell(r["path"] in marks), Text(r["path"]), r["path"] in run_files if self.kind == "changes": st = Text("M", style="bold " + WARN) if r["kind"] == "M" else Text("A", style="bold " + GOOD) return [mark, st, path, version_cell(r), holder_cell(r["holder"]), flags_cell(r, in_run)] if self.kind == "locks": return [mark, path, holder_cell(r["holder"], "free"), local_cell(r), flags_cell(r, in_run)] return [mark, path, local_cell(r), flags_cell(r, in_run)] class FilePane(Horizontal): """A file table with the detail pane for its highlighted row.""" def __init__(self, kind): super().__init__(classes="file-pane") self.kind = kind def compose(self): yield FileTable(self.kind) yield DetailPane(id="detail-" + self.kind) class DetailPane(Static): """Everything known about the highlighted file, plus what can be done with it.""" def show(self, kind, r, ws, in_run): if r is None: self.update(Text("Nothing here.", style=DIM)) return grid = Table.grid(padding=(0, 1)) grid.add_column(style=DIM, no_wrap=True) grid.add_column() if kind == "changes": grid.add_row("change", Text("new file" if r["kind"] == "A" else "modified", style=WARN)) if r["kind"] == "M": fresh = Text("stale - rebase (m)", style="bold " + BAD) if r["stale"] else \ Text("? could not read", style=WARN) if r["unknown"] else Text("✔ fresh", style=GOOD) grid.add_row("base", r["base"] or "?") grid.add_row("latest", Text.assemble((r["latest"] or "?", ""), (" ", ""), fresh)) else: grid.add_row("local copy", local_cell(r)) grid.add_row("lock", holder_cell(r.get("holder", ""), "free")) grid.add_row("hot file", Text("yes - locked on edit", style=HOT) if r.get("hot") else Text("no", style=DIM)) if in_run: grid.add_row("sanity", Text("in the current run", style=ACCENT)) try: st = os.stat(os.path.join(ws, r["path"])) grid.add_row("on disk", "%s %s" % (fmt_size(st.st_size), fmt_clock(st.st_mtime))) grid.add_row("writable", Text("yes", style=GOOD) if os.access(os.path.join(ws, r["path"]), os.W_OK) else Text("no (read-only copy)", style=DIM)) except OSError: grid.add_row("on disk", Text("missing", style=BAD)) keys = Table.grid(padding=(0, 1)) keys.add_column(style="bold " + ACCENT, no_wrap=True) keys.add_column(style=DIM) for key, text in HINTS[kind]: keys.add_row(key, text) self.update(Group(Text(r["path"], style="bold", overflow="fold"), Text("─" * 30, style=DIM), grid, Text(""), keys)) HINTS = { "changes": [("space", "mark"), ("s", "run sanity"), ("c", "check in"), ("t", "tag"), ("m", "rebase stale"), ("n", "add a new file")], "locks": [("space", "mark"), ("u", "release lock"), ("l", "lock"), ("t", "tag")], "checkout": [("space", "mark"), ("l", "lock"), ("t", "tag")], } def fmt_size(n): for unit in ("B", "KB", "MB"): if n < 1024: return "%d %s" % (n, unit) if unit == "B" else "%.1f %s" % (n, unit) n /= 1024.0 return "%.1f GB" % n # -- sanity run ---------------------------------------------------------------- STATUS_COLOUR = {"passed": GOOD, "failed": BAD, "error": BAD, "cancelled": WARN, "queued": ACCENT, "running": ACCENT} def status_pill(job, jstate): if jstate == "orphaned": return pill("RUNNER LOST", WARN) st = job.get("status", "?") return pill(st.upper(), STATUS_COLOUR.get(st, ACCENT)) def step_glyph(status, jstate): if status == "running": return Text("▲", style="bold " + WARN) if jstate == "orphaned" else Text(spinner(), style="bold " + ACCENT) return {"pending": Text("·", style=DIM), "done": Text("✔", style="bold " + GOOD), "failed": Text("✘", style="bold " + BAD), "cancelled": Text("–", style=WARN), "skipped": Text("–", style=DIM)}.get(status, Text("?")) def bar(frac, width, colour=ACCENT): """A thin progress bar; frac None sweeps back and forth (duration unknown).""" if frac is None: pos = int(time.time() * 12) % (2 * width) pos = pos if pos < width else 2 * width - pos - 1 lo, hi = max(0, pos - 2), min(width, pos + 3) return Text.assemble(("━" * lo, "grey23"), ("━" * (hi - lo), colour), ("━" * (width - hi), "grey23")) n = int(round(max(0.0, min(1.0, frac)) * width)) return Text.assemble(("━" * n, colour), ("━" * (width - n), "grey23")) def step_bar(s, width=26): if s.get("kind") != "sanity" or s["status"] in ("pending", "skipped"): return Text("") if s["status"] == "failed": return bar(1.0, width, BAD) if s["status"] != "running": return bar(1.0, width, GOOD) est = s.get("est") if not est or not s.get("t0"): return bar(None, width) return bar(min(0.99, (time.time() - s["t0"]) / est), width) def steps_table(job, jstate): t = Table.grid(padding=(0, 2)) for _ in range(5): t.add_column(no_wrap=True) for s in job["steps"]: st = s["status"] el = ((s.get("t1") or time.time()) - s["t0"]) if s.get("t0") else None timing = fmt_dur(el) if el is not None else ("~" + fmt_dur(s["est"]) if s.get("est") else "") if st == "running" and s.get("kind") == "sanity" and s.get("est"): timing = "%s / ~%s" % (fmt_dur(el), fmt_dur(s["est"])) label_style = DIM if st in ("pending", "skipped") else "bold" if st == "running" else "" detail = Text(s.get("detail") or "", style=BAD if st == "failed" else DIM) t.add_row(step_glyph(st, jstate), Text(s["label"], style=label_style), step_bar(s), Text(timing, style=ACCENT if st == "running" else DIM), detail) return t def run_heading(job, jstate): start = job.get("started") or job["created"] end = job.get("finished") or time.time() top = Table.grid(expand=True) top.add_column() top.add_column(justify="right") top.add_row(Text.assemble(("Run %s " % job["id"], "bold"), status_pill(job, jstate)), Text("started %s · elapsed %s" % (fmt_clock(start), fmt_dur(end - start)), style=DIM)) if job["mode"] == "checkin": mode = Text.assemble(("on pass ", DIM), ("check in", "bold " + GOOD)) if job.get("tag"): mode.append_text(Text.assemble((" → tag ", DIM), (job["tag"], "bold " + HOT))) mode.append_text(Text.assemble((" “%s”" % job.get("msg", ""), ""))) else: mode = Text.assemble(("on pass ", DIM), ("release locks only", "bold " + WARN), (" (check in later with c)", DIM)) files = job["files"] + job["new_files"] who = Text.assemble(("files ", DIM), (", ".join(files), ""), (" locked by run: %d" % len(job.get("locked_by_job", [])), ACCENT)) return Group(top, mode, who) class RunPanel(Vertical): """The Sanity run tab: step list with progress bars and a live tail of the current log.""" def compose(self): yield Static(EMPTY_RUN, id="run-empty") yield Static(id="run-head") yield Static(id="run-steps") yield Static(id="run-summary") yield RichLog(id="run-log", max_lines=4000, wrap=False, auto_scroll=True) def on_mount(self): self.tail = Tail() self.show(None, "none", {}) def show(self, job, jstate, _unused=None): has = job is not None for wid in ("#run-head", "#run-steps", "#run-summary", "#run-log"): self.query_one(wid).display = has self.query_one("#run-empty").display = not has if not has: return self.query_one("#run-head", Static).update(run_heading(job, jstate)) self.query_one("#run-steps", Static).update(steps_table(job, jstate)) summary = self.query_one("#run-summary", Static) if jstate == "orphaned": summary.update(Text("▲ No heartbeat from the runner for %s - it may have been killed. " "Press x to stop its simulation and release the %d lock(s) it took." % ( fmt_dur(time.time() - job.get("heartbeat", 0)), len(job.get("locked_by_job", []))), style="bold " + WARN)) elif jstate == "done" and job.get("summary"): summary.update(Text(job["summary"], style="bold " + (GOOD if job["status"] == "passed" else BAD))) else: summary.update("") logs = [s for s in job["steps"] if s.get("kind") == "sanity" and s.get("log") and s["status"] != "pending"] log = self.query_one("#run-log", RichLog) if logs: log.border_title = "log · %s" % os.path.basename(logs[-1]["log"]) self.tail.poll(logs[-1]["log"], log) else: log.border_title = "log" EMPTY_RUN = Text.assemble( ("No sanity run yet.\n\n", "bold"), ("1. In ", DIM), ("Changes", "bold"), (", mark files with ", DIM), ("space", "bold " + ACCENT), (" (no marks = the highlighted row).\n", DIM), ("2. Press ", DIM), ("s", "bold " + ACCENT), (": the files are locked, sanity runs on every config, and on pass\n" " they are checked in (or just unlocked). Locks are always released.\n", DIM), ("3. Follow it here, or from any shell: ", DIM), ("dsflow_tui.py status", "bold")) # -- logs ------------------------------------------------------------------------ def log_line(line): low = line.lower() style = BAD if ("error" in low or "fail" in low) else GOOD if ("pass" in low) else "" return Text(line, style=style) class Tail(object): """Follows one file into a RichLog: the last 256 KB first, then whatever gets appended.""" MAX_START = 256 * 1024 def __init__(self): self.path, self.pos, self.ino, self.partial = None, 0, None, "" def poll(self, path, log): try: st = os.stat(path) except OSError: st = None if path != self.path or st is None or st.st_ino != self.ino or st.st_size < self.pos: log.clear() self.path, self.pos, self.partial = path, 0, "" self.ino = st.st_ino if st else None if st is None: log.write(Text("(%s does not exist yet)" % path, style=DIM)) return if st.st_size == self.pos: return start = max(self.pos, st.st_size - self.MAX_START) with open(path, "rb") as fh: fh.seek(start) data = self.partial + fh.read().decode("utf-8", "replace").replace("\r", "") skipped = start > self.pos self.pos = st.st_size lines = data.split("\n") self.partial = lines.pop() if skipped and lines: lines = lines[1:] for line in lines: log.write(log_line(line.expandtabs(4))) class LogPanel(Vertical): """The Logs tab: one source at a time (sanity per config, the runner, this session's activity).""" def __init__(self, sources_fn, activity): super().__init__() self.sources_fn = sources_fn self.activity = activity self.shown_activity = 0 self.source = "activity" def compose(self): with Horizontal(id="log-bar"): yield Label("source", classes="log-label") yield Select(self.options(), value="activity", allow_blank=False, id="log-source") yield RichLog(id="log-view", max_lines=20000, wrap=False, auto_scroll=True) def on_mount(self): self.tail = Tail() def options(self): return [(name, name) for name, _ in self.sources_fn()] def on_select_changed(self, event): if event.value != self.source and event.value is not Select.BLANK: self.source = event.value self.tail = Tail() self.shown_activity = 0 self.query_one("#log-view", RichLog).clear() self.tick() def sync_sources(self): select = self.query_one("#log-source", Select) opts = self.options() if [v for _, v in opts] != getattr(self, "_opts", None): self._opts = [v for _, v in opts] select.set_options(opts) select.value = self.source if self.source in self._opts else "activity" def tick(self): log = self.query_one("#log-view", RichLog) if self.source == "activity": for ts, kind, text in self.activity[self.shown_activity:]: style = {"error": BAD, "warning": WARN, "information": ""}.get(kind, DIM) log.write(Text.assemble((fmt_clock(ts) + " ", DIM), (text, style))) self.shown_activity = len(self.activity) return path = dict(self.sources_fn()).get(self.source) if path: self.tail.poll(path, log) # -- bottom status line ------------------------------------------------------------ def run_bar(job, jstate, n_marked): right = Text("%d marked" % n_marked, style=ACCENT if n_marked else DIM) if jstate == "none": left = Text("○ no sanity run yet", style=DIM) elif jstate == "orphaned": left = Text("▲ runner lost - press x to release %d lock(s)" % len(job.get("locked_by_job", [])), style="bold " + WARN) elif jstate == "active": steps = job["steps"] cur = next((s for s in steps if s["status"] == "running"), None) san = [s for s in steps if s.get("kind") == "sanity"] done = sum(1 for s in san if s["status"] == "done") frac = 0.0 if cur is not None and cur.get("kind") == "sanity" and cur.get("est") and cur.get("t0"): frac = min(0.99, (time.time() - cur["t0"]) / cur["est"]) overall = (done + frac) / len(san) if san else 0 left = Text.assemble(pill("%s SANITY" % spinner(), ACCENT), (" %s " % (cur["label"] if cur else "starting"), "bold"), bar(overall if (done or frac) else None, 16), (" %d/%d cfg" % (done, len(san)), ACCENT), (" · %s" % fmt_dur(time.time() - (job.get("started") or job["created"])), DIM), (" · %d locked by run" % len(job.get("locked_by_job", [])), DIM)) else: left = Text.assemble(("last run ", DIM), status_pill(job, jstate), (" %s " % fmt_ago(job.get("finished")), DIM), (job.get("summary", ""), DIM)) grid = Table.grid(expand=True) grid.add_column(no_wrap=True, overflow="ellipsis", ratio=1) grid.add_column(no_wrap=True, justify="right") grid.add_row(left, right) return grid