|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""turtle-render — inline file renderer for TurtleTerm. |
| 3 | +
|
| 4 | +Renders files inside the terminal using protocol-appropriate methods: |
| 5 | + Images (.png .jpg .gif .webp .svg .bmp .ico) — iTerm2/WezTerm inline protocol |
| 6 | + PDFs (.pdf) — first page via pdftoppm/Pillow → inline image + metadata |
| 7 | + CSV (.csv .tsv) — aligned table printed inline |
| 8 | + JSON (.json) — colorized pretty-print |
| 9 | + TOML/YAML (.toml .yaml .yml) — syntax-highlighted via bat |
| 10 | + Markdown (.md .markdown) — rendered via mdcat or bat |
| 11 | + Code (anything else) — bat with syntax highlight + line numbers |
| 12 | +
|
| 13 | +Usage: |
| 14 | + turtle-render file.png |
| 15 | + turtle-render data.csv |
| 16 | + turtle-render --width 100 diagram.svg |
| 17 | + cat file.json | turtle-render --stdin --type json |
| 18 | + turtle-render file.pdf --page 2 |
| 19 | +""" |
| 20 | + |
| 21 | +from __future__ import annotations |
| 22 | + |
| 23 | +import argparse |
| 24 | +import base64 |
| 25 | +import csv |
| 26 | +import io |
| 27 | +import json |
| 28 | +import os |
| 29 | +import shutil |
| 30 | +import subprocess |
| 31 | +import sys |
| 32 | +from pathlib import Path |
| 33 | + |
| 34 | +# ── image rendering (iTerm2 / WezTerm inline protocol) ──────────────────────── |
| 35 | + |
| 36 | +def emit_image_bytes(data: bytes, filename: str = "", width: int = 0) -> None: |
| 37 | + b64 = base64.b64encode(data).decode("ascii") |
| 38 | + size = len(data) |
| 39 | + fn_b64 = base64.b64encode(filename.encode()).decode() if filename else "" |
| 40 | + parts = [f"size={size}", "inline=1"] |
| 41 | + if fn_b64: |
| 42 | + parts.append(f"name={fn_b64}") |
| 43 | + if width: |
| 44 | + parts.append(f"width={width}") |
| 45 | + sys.stdout.buffer.write(f"\x1b]1337;File={';'.join(parts)}:{b64}\x07\n".encode()) |
| 46 | + sys.stdout.buffer.flush() |
| 47 | + |
| 48 | + |
| 49 | +def render_image(path: Path, width: int = 0) -> bool: |
| 50 | + try: |
| 51 | + data = path.read_bytes() |
| 52 | + emit_image_bytes(data, path.name, width) |
| 53 | + dim_info = "" |
| 54 | + # Try to get dimensions via PIL |
| 55 | + try: |
| 56 | + from PIL import Image as _PILImage # type: ignore |
| 57 | + with _PILImage.open(path) as img: |
| 58 | + dim_info = f" {img.width}×{img.height} {img.mode}" |
| 59 | + except Exception: |
| 60 | + pass |
| 61 | + size_kb = len(data) / 1024 |
| 62 | + print(f"\033[2m {path.name} {size_kb:.1f}KB{dim_info}\033[0m") |
| 63 | + return True |
| 64 | + except Exception as e: |
| 65 | + print(f"render_image: {e}", file=sys.stderr) |
| 66 | + return False |
| 67 | + |
| 68 | + |
| 69 | +def render_svg(path: Path, width: int = 0) -> bool: |
| 70 | + # Try cairosvg → PNG → inline |
| 71 | + try: |
| 72 | + import cairosvg # type: ignore |
| 73 | + png_data = cairosvg.svg2png(url=str(path), output_width=800) |
| 74 | + emit_image_bytes(png_data, path.name, width or 80) |
| 75 | + print(f"\033[2m {path.name} (SVG→PNG)\033[0m") |
| 76 | + return True |
| 77 | + except Exception: |
| 78 | + pass |
| 79 | + # Fallback: show as source code |
| 80 | + return render_code(path) |
| 81 | + |
| 82 | + |
| 83 | +# ── PDF rendering ────────────────────────────────────────────────────────────── |
| 84 | + |
| 85 | +def render_pdf(path: Path, page: int = 1, width: int = 0) -> bool: |
| 86 | + # Try pdftoppm (poppler-utils) |
| 87 | + if shutil.which("pdftoppm"): |
| 88 | + try: |
| 89 | + result = subprocess.run( |
| 90 | + ["pdftoppm", "-r", "144", "-f", str(page), "-l", str(page), |
| 91 | + "-png", "-singlefile", str(path), "/tmp/turtle-pdf-render"], |
| 92 | + capture_output=True, timeout=15, |
| 93 | + ) |
| 94 | + png_path = Path("/tmp/turtle-pdf-render.png") |
| 95 | + if png_path.exists(): |
| 96 | + data = png_path.read_bytes() |
| 97 | + emit_image_bytes(data, f"{path.name} (p{page})", width or 80) |
| 98 | + png_path.unlink(missing_ok=True) |
| 99 | + # Show metadata |
| 100 | + _show_pdf_meta(path) |
| 101 | + return True |
| 102 | + except Exception: |
| 103 | + pass |
| 104 | + |
| 105 | + # Try Pillow (PDF support requires Pillow + poppler or pdf2image) |
| 106 | + try: |
| 107 | + from pdf2image import convert_from_path # type: ignore |
| 108 | + imgs = convert_from_path(str(path), first_page=page, last_page=page, dpi=144) |
| 109 | + if imgs: |
| 110 | + buf = io.BytesIO() |
| 111 | + imgs[0].save(buf, format="PNG") |
| 112 | + emit_image_bytes(buf.getvalue(), f"{path.name} (p{page})", width or 80) |
| 113 | + _show_pdf_meta(path) |
| 114 | + return True |
| 115 | + except Exception: |
| 116 | + pass |
| 117 | + |
| 118 | + # Final fallback: metadata only |
| 119 | + return _show_pdf_meta(path) |
| 120 | + |
| 121 | + |
| 122 | +def _show_pdf_meta(path: Path) -> bool: |
| 123 | + meta_lines = [f"\033[38;2;88;166;255m◆ PDF\033[0m {path.name}"] |
| 124 | + if shutil.which("pdfinfo"): |
| 125 | + try: |
| 126 | + out = subprocess.check_output(["pdfinfo", str(path)], timeout=5, text=True) |
| 127 | + for line in out.splitlines()[:8]: |
| 128 | + if any(k in line for k in ("Pages:", "Title:", "Author:", "Creator:", "File size")): |
| 129 | + meta_lines.append(f" \033[2m{line.strip()}\033[0m") |
| 130 | + except Exception: |
| 131 | + pass |
| 132 | + print("\n".join(meta_lines)) |
| 133 | + return True |
| 134 | + |
| 135 | + |
| 136 | +# ── CSV / TSV rendering ──────────────────────────────────────────────────────── |
| 137 | + |
| 138 | +def render_csv(path: Path | None = None, text: str | None = None, max_rows: int = 40) -> bool: |
| 139 | + try: |
| 140 | + if path: |
| 141 | + text = path.read_text(errors="replace") |
| 142 | + if not text: |
| 143 | + return False |
| 144 | + |
| 145 | + dialect = "excel-tab" if (path and path.suffix == ".tsv") else "excel" |
| 146 | + reader = csv.reader(io.StringIO(text), dialect=dialect) |
| 147 | + rows = list(reader) |
| 148 | + if not rows: |
| 149 | + print("(empty CSV)") |
| 150 | + return True |
| 151 | + |
| 152 | + header = rows[0] |
| 153 | + data_rows = rows[1:max_rows + 1] |
| 154 | + truncated = len(rows) - 1 > max_rows |
| 155 | + |
| 156 | + # Compute column widths |
| 157 | + col_w = [len(h) for h in header] |
| 158 | + for row in data_rows: |
| 159 | + for i, cell in enumerate(row): |
| 160 | + if i < len(col_w): |
| 161 | + col_w[i] = max(col_w[i], min(len(cell), 40)) |
| 162 | + |
| 163 | + def fmt_row(row: list[str], color: str = "") -> str: |
| 164 | + cells = [] |
| 165 | + for i, cell in enumerate(row): |
| 166 | + w = col_w[i] if i < len(col_w) else 10 |
| 167 | + cells.append(cell[:w].ljust(w)) |
| 168 | + return color + " " + " │ ".join(cells) + "\033[0m" |
| 169 | + |
| 170 | + sep = " " + "──┼──".join("─" * w for w in col_w) |
| 171 | + |
| 172 | + print() |
| 173 | + print(fmt_row(header, "\033[38;2;88;166;255m\033[1m")) |
| 174 | + print(f"\033[2m{sep}\033[0m") |
| 175 | + for row in data_rows: |
| 176 | + print(fmt_row(row)) |
| 177 | + if truncated: |
| 178 | + print(f"\033[2m … {len(rows)-1-max_rows} more rows\033[0m") |
| 179 | + print(f"\033[2m {len(header)} columns · {len(rows)-1} rows\033[0m") |
| 180 | + print() |
| 181 | + return True |
| 182 | + except Exception as e: |
| 183 | + print(f"render_csv: {e}", file=sys.stderr) |
| 184 | + return False |
| 185 | + |
| 186 | + |
| 187 | +# ── JSON rendering ───────────────────────────────────────────────────────────── |
| 188 | + |
| 189 | +def render_json(path: Path | None = None, text: str | None = None) -> bool: |
| 190 | + if path: |
| 191 | + text = path.read_text(errors="replace") |
| 192 | + if not text: |
| 193 | + return False |
| 194 | + |
| 195 | + # Try bat for syntax highlight first |
| 196 | + if shutil.which("bat"): |
| 197 | + try: |
| 198 | + subprocess.run( |
| 199 | + ["bat", "--language=json", "--style=numbers,header-filename", |
| 200 | + "--color=always", "--paging=never"] + |
| 201 | + ([str(path)] if path else []), |
| 202 | + input=text.encode() if not path else None, |
| 203 | + check=False, timeout=10, |
| 204 | + ) |
| 205 | + return True |
| 206 | + except Exception: |
| 207 | + pass |
| 208 | + |
| 209 | + # Fallback: python pretty-print |
| 210 | + try: |
| 211 | + parsed = json.loads(text) |
| 212 | + pretty = json.dumps(parsed, indent=2, ensure_ascii=False) |
| 213 | + print(pretty[:8000]) |
| 214 | + if len(pretty) > 8000: |
| 215 | + print("\033[2m … truncated\033[0m") |
| 216 | + return True |
| 217 | + except json.JSONDecodeError as e: |
| 218 | + print(f"JSON parse error: {e}", file=sys.stderr) |
| 219 | + return False |
| 220 | + |
| 221 | + |
| 222 | +# ── markdown rendering ───────────────────────────────────────────────────────── |
| 223 | + |
| 224 | +def render_markdown(path: Path) -> bool: |
| 225 | + for cmd in [["mdcat", str(path)], ["glow", str(path)], ["bat", "--language=md", "--style=full", str(path)]]: |
| 226 | + if shutil.which(cmd[0]): |
| 227 | + try: |
| 228 | + subprocess.run(cmd, check=False, timeout=15) |
| 229 | + return True |
| 230 | + except Exception: |
| 231 | + pass |
| 232 | + return render_code(path) |
| 233 | + |
| 234 | + |
| 235 | +# ── generic code rendering ───────────────────────────────────────────────────── |
| 236 | + |
| 237 | +def render_code(path: Path) -> bool: |
| 238 | + if shutil.which("bat"): |
| 239 | + try: |
| 240 | + subprocess.run( |
| 241 | + ["bat", "--style=numbers,header-filename,grid", "--color=always", "--paging=never", str(path)], |
| 242 | + check=False, timeout=15, |
| 243 | + ) |
| 244 | + return True |
| 245 | + except Exception: |
| 246 | + pass |
| 247 | + try: |
| 248 | + print(path.read_text(errors="replace")) |
| 249 | + return True |
| 250 | + except Exception as e: |
| 251 | + print(f"render_code: {e}", file=sys.stderr) |
| 252 | + return False |
| 253 | + |
| 254 | + |
| 255 | +# ── dispatcher ───────────────────────────────────────────────────────────────── |
| 256 | + |
| 257 | +IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".ico", ".tiff", ".tif", ".avif"} |
| 258 | +CODE_EXTS = {".py", ".js", ".ts", ".tsx", ".jsx", ".rs", ".go", ".c", ".cpp", ".h", |
| 259 | + ".java", ".rb", ".sh", ".bash", ".zsh", ".lua", ".toml", ".yaml", ".yml", |
| 260 | + ".tf", ".hcl", ".sql", ".css", ".scss", ".html", ".xml", ".dockerfile"} |
| 261 | + |
| 262 | + |
| 263 | +def render_file(path: Path, width: int = 0, page: int = 1) -> bool: |
| 264 | + ext = path.suffix.lower() |
| 265 | + |
| 266 | + if ext in IMAGE_EXTS: |
| 267 | + return render_image(path, width) |
| 268 | + if ext == ".svg": |
| 269 | + return render_svg(path, width) |
| 270 | + if ext == ".pdf": |
| 271 | + return render_pdf(path, page, width) |
| 272 | + if ext in {".csv", ".tsv"}: |
| 273 | + return render_csv(path) |
| 274 | + if ext == ".json": |
| 275 | + return render_json(path) |
| 276 | + if ext in {".md", ".markdown"}: |
| 277 | + return render_markdown(path) |
| 278 | + if ext in CODE_EXTS or path.stat().st_size < 512 * 1024: |
| 279 | + return render_code(path) |
| 280 | + |
| 281 | + # Binary / unknown: show metadata |
| 282 | + size = path.stat().st_size |
| 283 | + print(f"\033[38;2;139;148;158m {path.name} {size/1024:.1f}KB (binary — no renderer)\033[0m") |
| 284 | + return True |
| 285 | + |
| 286 | + |
| 287 | +# ── main ─────────────────────────────────────────────────────────────────────── |
| 288 | + |
| 289 | +def main(): |
| 290 | + parser = argparse.ArgumentParser(description="TurtleTerm inline file renderer") |
| 291 | + parser.add_argument("files", nargs="*") |
| 292 | + parser.add_argument("--width", type=int, default=0, help="image width in columns") |
| 293 | + parser.add_argument("--page", type=int, default=1, help="PDF page number") |
| 294 | + parser.add_argument("--stdin", action="store_true", help="read from stdin") |
| 295 | + parser.add_argument("--type", default="", help="force file type (json/csv/image/code)") |
| 296 | + args = parser.parse_args() |
| 297 | + |
| 298 | + ok = True |
| 299 | + |
| 300 | + if args.stdin or (not args.files and not sys.stdin.isatty()): |
| 301 | + data = sys.stdin.buffer.read() |
| 302 | + ftype = args.type.lower() |
| 303 | + if ftype == "image": |
| 304 | + emit_image_bytes(data, "stdin", args.width) |
| 305 | + elif ftype in ("json", ""): |
| 306 | + try: |
| 307 | + json.loads(data) |
| 308 | + render_json(text=data.decode(errors="replace")) |
| 309 | + except Exception: |
| 310 | + render_csv(text=data.decode(errors="replace")) |
| 311 | + elif ftype == "csv": |
| 312 | + render_csv(text=data.decode(errors="replace")) |
| 313 | + else: |
| 314 | + sys.stdout.buffer.write(data) |
| 315 | + return |
| 316 | + |
| 317 | + for fname in args.files: |
| 318 | + path = Path(fname).expanduser() |
| 319 | + if not path.exists(): |
| 320 | + print(f"turtle-render: not found: {fname}", file=sys.stderr) |
| 321 | + ok = False |
| 322 | + continue |
| 323 | + if not render_file(path, args.width, args.page): |
| 324 | + ok = False |
| 325 | + |
| 326 | + sys.exit(0 if ok else 1) |
| 327 | + |
| 328 | + |
| 329 | +if __name__ == "__main__": |
| 330 | + main() |
0 commit comments