mintterm 0.2.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.
mintterm/app.py ADDED
@@ -0,0 +1,765 @@
1
+ """pygame front end for mintterm."""
2
+
3
+ import os
4
+ import shlex
5
+ import shutil
6
+ import subprocess
7
+ import threading
8
+ import time
9
+
10
+ import pygame
11
+
12
+ from . import clipboard, helper, prompt, safety, storage, trash, views
13
+ from .branding import make_icon
14
+ from .runner import Block, cancel, run
15
+ from .themes import THEMES
16
+
17
+ WIDTH, HEIGHT = 1000, 680
18
+ PAD = 12
19
+ KEY_COLS = 20 # width of the key column in key-value rows, in characters
20
+ BAR_COLS = 22 # where bars start in bar rows, in characters
21
+ BAR_PX = 240
22
+ MAX_OUT_LINES = 500
23
+ MAX_BLOCKS = 300
24
+ TOAST_SECONDS = 2.5
25
+ THEME_ORDER = list(THEMES)
26
+
27
+ WELCOME = [
28
+ "Real bash runs underneath, so your commands work as they always did.",
29
+ "Each command becomes a card. Click a card's prompt line to fold it.",
30
+ "ls, df, du, ps, free, ip, ss, git status, git log, grep, find and more appear as tables and bars.",
31
+ "rm moves files to the mintterm trash, so undo can bring them back.",
32
+ "Try: ls df ps git status ? find big files set theme sunset",
33
+ ]
34
+
35
+ HELP_LINES = [
36
+ "Tables and bars: ls, df, du, ps, free, ip, ss, git status, git log, grep, find,",
37
+ " apt list --upgradable, systemctl --failed",
38
+ "Safety: rm moves to trash (undo restores it). rm --really deletes permanently.",
39
+ " rm -rf, dd, mkfs and chmod -R show a preview and wait for y.",
40
+ "Ask: ? find big files ? explain tar",
41
+ "Settings: set theme sunset | set profile Server | set font 18 | set segments user,path",
42
+ " set notify 10 (desktop alert after 10 seconds when the window is in the background)",
43
+ "Builtins: help, history, clear, undo",
44
+ "Keys: Tab complete · Ctrl+R search history · Ctrl+P pin card · Ctrl+Shift+C copy output",
45
+ " Ctrl+T next theme · Ctrl+C stop a running command · Ctrl+U clear line · Esc quit",
46
+ ]
47
+
48
+
49
+ def text_view(lines):
50
+ return views.text_view(lines)
51
+
52
+
53
+ def parse_pct(cell):
54
+ return views.parse_pct(cell)
55
+
56
+
57
+ class App:
58
+ def __init__(self, cfg):
59
+ pygame.init()
60
+ pygame.key.set_repeat(400, 35)
61
+ pygame.display.set_caption("mintterm")
62
+ pygame.display.set_icon(make_icon())
63
+ self.screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
64
+ self.clock = pygame.time.Clock()
65
+
66
+ self.cfg = cfg
67
+ self.user, self.host = prompt.identity()
68
+ self.cwd = os.path.expanduser("~")
69
+ self.branch = prompt.git_branch(self.cwd)
70
+ self.last_ok = True
71
+
72
+ self.input = ""
73
+ self.history = storage.load_history()
74
+ self.hist_i = len(self.history)
75
+ self.blocks = [Block(command="", cwd=self.cwd, view=text_view(WELCOME))]
76
+ self.undo_stack = []
77
+
78
+ self.pending = None # a risky command waiting for y
79
+ self.search = None # history search text, or None when not searching
80
+ self.search_idx = 0
81
+ self.selected = None # last clicked card
82
+
83
+ self.worker = None # thread running the current command
84
+ self.holder = [] # Popen objects for the current command
85
+ self.running_block = None
86
+
87
+ self.scroll = 0
88
+ self.visible = []
89
+ self.toast_text = ""
90
+ self.toast_until = 0.0
91
+
92
+ self.version = 0
93
+ self._rows = None
94
+ self._rows_version = -1
95
+ self.running = True
96
+
97
+ self.apply_settings()
98
+ pygame.key.start_text_input()
99
+
100
+ # ---- settings ----------------------------------------------------------
101
+
102
+ def apply_settings(self):
103
+ self.theme = THEMES.get(self.cfg["theme"], THEMES["mint-dark"])
104
+ self.font = pygame.font.SysFont("ubuntumono,dejavusansmono,monospace", int(self.cfg["font_size"]))
105
+ self.char_w = self.font.size("M")[0]
106
+ self.line_h = self.font.get_linesize() + 4
107
+ self.touch()
108
+
109
+ @property
110
+ def prod(self):
111
+ return storage.PROFILES.get(self.cfg["profile"], {}).get("prod", False)
112
+
113
+ def color(self, key):
114
+ t = self.theme
115
+ if key is None:
116
+ return t["fg"]
117
+ if key == "prompt" and self.prod:
118
+ return t["prod"]
119
+ return t.get(key, t["fg"])
120
+
121
+ def touch(self):
122
+ self.version += 1
123
+
124
+ # ---- main loop ---------------------------------------------------------
125
+
126
+ def run(self):
127
+ while self.running:
128
+ for event in pygame.event.get():
129
+ self.handle(event)
130
+ self.poll_worker()
131
+ self.draw()
132
+ pygame.display.flip()
133
+ self.clock.tick(30)
134
+ if self.holder:
135
+ cancel(self.holder[-1])
136
+ pygame.quit()
137
+
138
+ # ---- events ------------------------------------------------------------
139
+
140
+ def handle(self, event):
141
+ if event.type == pygame.QUIT:
142
+ self.running = False
143
+ elif event.type == pygame.VIDEORESIZE:
144
+ self.screen = pygame.display.get_surface()
145
+ self.touch()
146
+ elif event.type == pygame.TEXTINPUT:
147
+ if self.search is not None:
148
+ self.search += event.text
149
+ self.search_idx = 0
150
+ else:
151
+ self.input += event.text
152
+ self.scroll = 0
153
+ self.touch()
154
+ elif event.type == pygame.MOUSEWHEEL:
155
+ self.scroll = max(0, self.scroll + event.y * 3)
156
+ elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
157
+ self.click(event.pos)
158
+ elif event.type == pygame.KEYDOWN:
159
+ self.key(event)
160
+
161
+ def key(self, event):
162
+ ctrl = bool(event.mod & pygame.KMOD_CTRL)
163
+ shift = bool(event.mod & pygame.KMOD_SHIFT)
164
+ k = event.key
165
+
166
+ if ctrl and shift and k == pygame.K_c:
167
+ self.copy_output()
168
+ elif k == pygame.K_ESCAPE:
169
+ if self.search is not None:
170
+ self.search = None
171
+ self.touch()
172
+ else:
173
+ self.running = False
174
+ elif k in (pygame.K_RETURN, pygame.K_KP_ENTER):
175
+ self.submit()
176
+ elif k == pygame.K_BACKSPACE:
177
+ if self.search is not None:
178
+ self.search = self.search[:-1]
179
+ self.search_idx = 0
180
+ else:
181
+ self.input = self.input[:-1]
182
+ self.touch()
183
+ elif k == pygame.K_TAB:
184
+ self.complete()
185
+ elif k == pygame.K_UP:
186
+ self.step(-1)
187
+ elif k == pygame.K_DOWN:
188
+ self.step(1)
189
+ elif ctrl and k == pygame.K_c:
190
+ if self.worker is not None:
191
+ if self.holder:
192
+ cancel(self.holder[-1])
193
+ self.flash("Stopping...")
194
+ elif self.pending is not None:
195
+ self.pending = None
196
+ self.note_block("", text_view(["Cancelled. Nothing changed."]))
197
+ else:
198
+ self.input = ""
199
+ self.touch()
200
+ elif ctrl and k == pygame.K_l:
201
+ self.blocks.clear()
202
+ self.scroll = 0
203
+ self.touch()
204
+ elif ctrl and k == pygame.K_u:
205
+ self.input = ""
206
+ self.touch()
207
+ elif ctrl and k == pygame.K_r:
208
+ self.search = "" if self.search is None else None
209
+ self.search_idx = 0
210
+ self.touch()
211
+ elif ctrl and k == pygame.K_p:
212
+ self.toggle_pin()
213
+ elif ctrl and k == pygame.K_t:
214
+ self.cycle_theme()
215
+
216
+ def click(self, pos):
217
+ x, y = pos
218
+ if y < PAD:
219
+ return
220
+ idx = (y - PAD) // self.line_h
221
+ if idx >= len(self.visible):
222
+ return
223
+ kind, _, block = self.visible[idx]
224
+ if kind == "prompt" and block is not None:
225
+ block.folded = not block.folded
226
+ self.selected = block
227
+ self.touch()
228
+
229
+ def step(self, direction):
230
+ if self.search is not None:
231
+ count = len(self.search_matches()[:6])
232
+ self.search_idx = min(max(self.search_idx + direction, 0), max(0, count - 1))
233
+ self.touch()
234
+ return
235
+ if not self.history:
236
+ return
237
+ self.hist_i = min(max(self.hist_i + direction, 0), len(self.history))
238
+ self.input = self.history[self.hist_i] if self.hist_i < len(self.history) else ""
239
+ self.touch()
240
+
241
+ def search_matches(self):
242
+ query = (self.search or "").lower()
243
+ seen = []
244
+ for entry in reversed(self.history):
245
+ if query in entry.lower() and entry not in seen:
246
+ seen.append(entry)
247
+ return seen
248
+
249
+ def complete(self):
250
+ new_line, options = helper.complete(self.input, self.cwd)
251
+ self.input = new_line
252
+ self.touch()
253
+ if len(options) > 1:
254
+ self.note_block("", text_view([" ".join(options[:60])]))
255
+
256
+ # ---- submitting commands -----------------------------------------------
257
+
258
+ def submit(self):
259
+ if self.search is not None:
260
+ matches = self.search_matches()[:6]
261
+ if matches:
262
+ self.input = matches[min(self.search_idx, len(matches) - 1)]
263
+ self.search = None
264
+ self.search_idx = 0
265
+ self.touch()
266
+ return
267
+
268
+ text = self.input.strip()
269
+ self.input = ""
270
+ self.scroll = 0
271
+ self.touch()
272
+
273
+ if self.pending is not None:
274
+ command, self.pending = self.pending, None
275
+ if text.lower() in ("y", "yes"):
276
+ self.run_command(command)
277
+ else:
278
+ self.note_block("", text_view(["Cancelled. Nothing changed."]))
279
+ return
280
+
281
+ if not text:
282
+ return
283
+ if self.worker is not None:
284
+ self.input = text
285
+ self.touch()
286
+ self.flash("Still running. Ctrl+C stops it.")
287
+ return
288
+
289
+ self.history.append(text)
290
+ self.hist_i = len(self.history)
291
+ storage.append_history(text)
292
+
293
+ if self.builtin(text):
294
+ return
295
+ if safety.needs_confirmation(text):
296
+ self.pending = text
297
+ lines = safety.preview(text, self.cwd) + ["", "Type y and press Enter to run it. Anything else cancels."]
298
+ self.note_block("", text_view(lines))
299
+ return
300
+ self.run_command(text)
301
+
302
+ def builtin(self, text):
303
+ """Handle commands that do not run in bash. Returns True if handled."""
304
+ if text.startswith("?"):
305
+ self.note_block(text, helper.ask(text[1:]))
306
+ return True
307
+
308
+ head = text.split(maxsplit=1)
309
+ cmd = head[0]
310
+ rest = head[1].strip() if len(head) > 1 else ""
311
+
312
+ if cmd == "clear":
313
+ self.blocks.clear()
314
+ self.touch()
315
+ return True
316
+ if cmd == "help":
317
+ self.note_block(text, text_view(HELP_LINES))
318
+ return True
319
+ if cmd == "history":
320
+ recent = self.history[-50:]
321
+ start = len(self.history) - len(recent)
322
+ rows = [[str(start + i + 1), h] for i, h in enumerate(recent)]
323
+ self.note_block(text, [views.table(["#", "command"], rows)])
324
+ return True
325
+ if cmd == "undo":
326
+ self.do_undo()
327
+ return True
328
+ if cmd == "set":
329
+ self.do_set(text, rest)
330
+ return True
331
+ return False
332
+
333
+ def run_command(self, text):
334
+ """Run a command that has already been confirmed (if it needed it)."""
335
+ head = text.split(maxsplit=1)
336
+ if not head:
337
+ return
338
+ prog = os.path.basename(head[0])
339
+ rest = head[1] if len(head) > 1 else ""
340
+
341
+ if prog == "rm" and "--really" not in rest.split():
342
+ self.do_trash(text)
343
+ return
344
+ if prog == "rm":
345
+ text = text.replace("--really", "", 1)
346
+ on_success = self.mv_undo(text) if prog == "mv" else None
347
+ self.execute(text, on_success)
348
+
349
+ def execute(self, command, on_success=None):
350
+ run_cmd, render = views.plan(command)
351
+ block = Block(
352
+ command=command,
353
+ cwd=self.cwd,
354
+ prompt=self.make_prompt(),
355
+ running=True,
356
+ render=render,
357
+ on_success=on_success,
358
+ )
359
+ self.add_block(block)
360
+ self.holder = []
361
+ self.running_block = block
362
+ holder = self.holder
363
+ block_cwd = block.cwd
364
+
365
+ def work():
366
+ block.result = run(run_cmd, block_cwd, holder=holder)
367
+
368
+ self.worker = threading.Thread(target=work, daemon=True)
369
+ self.worker.start()
370
+
371
+ def poll_worker(self):
372
+ """Runs in the UI thread. Copies a finished command's result into its card."""
373
+ if self.worker is None or self.worker.is_alive():
374
+ return
375
+ block = self.running_block
376
+ self.worker = None
377
+ self.running_block = None
378
+ self.holder = []
379
+ res = block.result
380
+ block.result = None
381
+ block.running = False
382
+
383
+ if res is None:
384
+ block.code = 1
385
+ block.output = "The command could not start."
386
+ block.view = text_view([block.output])
387
+ else:
388
+ block.output = res.output
389
+ block.code = res.code
390
+ block.seconds = res.seconds
391
+ ok = res.code == 0
392
+ block.view = None
393
+ if ok and block.render is not None:
394
+ try:
395
+ block.view = block.render(res)
396
+ except Exception:
397
+ block.view = None
398
+ if block.view is None:
399
+ block.view = text_view(res.output.splitlines())
400
+ self.cwd = res.cwd
401
+ self.last_ok = ok
402
+ if ok and block.on_success is not None:
403
+ block.on_success()
404
+ if block.seconds >= self.cfg["notify_after"] and not pygame.key.get_focused():
405
+ self.notify(block)
406
+
407
+ self.branch = prompt.git_branch(self.cwd)
408
+ self.touch()
409
+
410
+ def notify(self, block):
411
+ if shutil.which("notify-send") is None:
412
+ return
413
+ status = "finished" if block.code == 0 else f"stopped with exit {block.code}"
414
+ message = f"{block.command} {status} after {block.seconds:.0f}s"
415
+ try:
416
+ subprocess.run(["notify-send", "--app-name=mintterm", "mintterm", message], timeout=2)
417
+ except (OSError, subprocess.SubprocessError):
418
+ pass
419
+
420
+ # ---- rm, mv, undo ------------------------------------------------------
421
+
422
+ def do_trash(self, text):
423
+ try:
424
+ args = shlex.split(text)[1:]
425
+ except ValueError:
426
+ self.note_block(text, text_view(["Could not read that command. Check the quotes."]), code=1)
427
+ return
428
+ paths = safety.expand(args, self.cwd)
429
+ if not paths:
430
+ self.note_block(text, text_view(["rm: nothing to remove. Give it a file name."]), code=1)
431
+ return
432
+
433
+ action, errors = trash.move_to_trash(paths)
434
+ lines = []
435
+ if action is not None:
436
+ self.undo_stack.append(action)
437
+ lines.append(f"Moved {len(action.pairs)} item(s) to the mintterm trash. Type undo to restore.")
438
+ lines += errors
439
+ failed = action is None
440
+ self.note_block(text, text_view(lines), code=1 if failed else None)
441
+
442
+ def mv_undo(self, text):
443
+ """Work out where mv will put things, so undo can move them back. Returns a callback or None."""
444
+ try:
445
+ args = shlex.split(text)[1:]
446
+ except ValueError:
447
+ return None
448
+ sources = safety.expand(args[:-1], self.cwd) if len(args) >= 2 else []
449
+ if len(args) < 2:
450
+ return None
451
+ dest = os.path.join(self.cwd, os.path.expanduser(args[-1]))
452
+
453
+ if os.path.isdir(dest):
454
+ pairs = [
455
+ (os.path.join(dest, os.path.basename(src.rstrip(os.sep))), os.path.abspath(src))
456
+ for src in sources
457
+ ]
458
+ elif len(sources) == 1:
459
+ pairs = [(os.path.abspath(dest), os.path.abspath(sources[0]))]
460
+ else:
461
+ return None
462
+ if not pairs:
463
+ return None
464
+
465
+ def record():
466
+ self.undo_stack.append(trash.Action(f"moved {len(pairs)} item(s)", pairs))
467
+
468
+ return record
469
+
470
+ def do_undo(self):
471
+ if not self.undo_stack:
472
+ self.note_block("undo", text_view(["Nothing to undo."]))
473
+ return
474
+ action = self.undo_stack.pop()
475
+ restored, errors = trash.undo(action)
476
+ lines = [f"Restored {restored} item(s)."] + errors
477
+ self.note_block("undo", text_view(lines), code=1 if errors else None)
478
+
479
+ # ---- settings ----------------------------------------------------------
480
+
481
+ def do_set(self, text, rest):
482
+ if not rest:
483
+ pairs = [
484
+ ("theme", self.cfg["theme"]),
485
+ ("font", str(self.cfg["font_size"])),
486
+ ("profile", self.cfg["profile"]),
487
+ ("segments", ", ".join(self.cfg["segments"])),
488
+ ("notify", f"{self.cfg['notify_after']}s"),
489
+ ]
490
+ self.note_block(text, views.kv_view(pairs))
491
+ return
492
+
493
+ parts = rest.split(maxsplit=1)
494
+ key = parts[0]
495
+ value = parts[1].strip() if len(parts) > 1 else ""
496
+ error = None
497
+
498
+ if key == "theme":
499
+ if value in THEMES:
500
+ self.cfg["theme"] = value
501
+ else:
502
+ error = f"Unknown theme. Choose: {', '.join(THEMES)}"
503
+ elif key == "profile":
504
+ if value in storage.PROFILES:
505
+ self.cfg["profile"] = value
506
+ self.cfg["segments"] = list(storage.PROFILES[value]["segments"])
507
+ else:
508
+ error = f"Unknown profile. Choose: {', '.join(storage.PROFILES)}"
509
+ elif key == "font":
510
+ if value.isdigit() and 10 <= int(value) <= 28:
511
+ self.cfg["font_size"] = int(value)
512
+ else:
513
+ error = "Font size must be a number from 10 to 28."
514
+ elif key == "segments":
515
+ chosen = [s for s in value.replace(" ", "").split(",") if s in storage.SEGMENTS]
516
+ if chosen:
517
+ self.cfg["segments"] = chosen
518
+ else:
519
+ error = f"Choose from: {', '.join(storage.SEGMENTS)}"
520
+ elif key == "notify":
521
+ if value.isdigit():
522
+ self.cfg["notify_after"] = int(value)
523
+ else:
524
+ error = "Give a number of seconds, for example: set notify 10"
525
+ else:
526
+ error = f"Unknown setting '{key}'. Try theme, profile, font, segments, or notify."
527
+
528
+ if error:
529
+ self.note_block(text, text_view([error]), code=1)
530
+ return
531
+ storage.save_config(self.cfg)
532
+ self.apply_settings()
533
+ self.note_block(text, text_view(["Saved."]))
534
+
535
+ def cycle_theme(self):
536
+ current = self.cfg["theme"]
537
+ if current in THEME_ORDER:
538
+ nxt = THEME_ORDER[(THEME_ORDER.index(current) + 1) % len(THEME_ORDER)]
539
+ else:
540
+ nxt = THEME_ORDER[0]
541
+ self.cfg["theme"] = nxt
542
+ storage.save_config(self.cfg)
543
+ self.apply_settings()
544
+ self.flash(f"Theme: {nxt}")
545
+
546
+ # ---- cards: pin, copy, flash ------------------------------------------
547
+
548
+ def last_command_block(self):
549
+ for block in reversed(self.blocks):
550
+ if block.command:
551
+ return block
552
+ return None
553
+
554
+ def selected_block(self):
555
+ if self.selected is not None and any(b is self.selected for b in self.blocks):
556
+ return self.selected
557
+ return self.last_command_block()
558
+
559
+ def toggle_pin(self):
560
+ block = self.selected_block()
561
+ if block is None:
562
+ return
563
+ block.pinned = not block.pinned
564
+ self.flash("Pinned to top" if block.pinned else "Unpinned")
565
+ self.touch()
566
+
567
+ def copy_output(self):
568
+ block = self.selected_block()
569
+ text = block.output if block is not None else ""
570
+ if not text:
571
+ self.flash("Nothing to copy")
572
+ return
573
+ if clipboard.copy_text(text):
574
+ self.flash("Copied output")
575
+ else:
576
+ self.flash("No clipboard tool. Install one: sudo apt install xclip")
577
+
578
+ def flash(self, message):
579
+ self.toast_text = message
580
+ self.toast_until = time.monotonic() + TOAST_SECONDS
581
+
582
+ # ---- blocks ------------------------------------------------------------
583
+
584
+ def make_prompt(self):
585
+ return prompt.build(
586
+ segments=self.cfg["segments"],
587
+ cwd=self.cwd,
588
+ ok=self.last_ok,
589
+ branch=self.branch,
590
+ venv=os.environ.get("VIRTUAL_ENV"),
591
+ user=self.user,
592
+ host=self.host,
593
+ now=time.strftime("%H:%M"),
594
+ )
595
+
596
+ def add_block(self, block):
597
+ self.blocks.append(block)
598
+ if len(self.blocks) > MAX_BLOCKS:
599
+ del self.blocks[0]
600
+ self.scroll = 0
601
+ self.touch()
602
+
603
+ def note_block(self, command, view, code=None):
604
+ block = Block(
605
+ command=command,
606
+ cwd=self.cwd,
607
+ prompt=self.make_prompt() if command else [],
608
+ view=view,
609
+ code=code,
610
+ )
611
+ self.add_block(block)
612
+ return block
613
+
614
+ # ---- building rows -----------------------------------------------------
615
+
616
+ def rows(self):
617
+ if self._rows is None or self._rows_version != self.version:
618
+ self._rows = self.build_rows()
619
+ self._rows_version = self.version
620
+ return self._rows
621
+
622
+ def build_rows(self):
623
+ """Flatten cards into one row per line. Each row is (kind, payload, block)."""
624
+ rows = []
625
+ ordered = [b for b in self.blocks if b.pinned] + [b for b in self.blocks if not b.pinned]
626
+ for block in ordered:
627
+ if block.command:
628
+ marker = "◆ " if block.pinned else ("▸ " if block.folded else "▾ ")
629
+ rows.append(("prompt", ([(marker, "muted")] + block.prompt, block.command), block))
630
+ if block.folded:
631
+ continue
632
+ if block.running:
633
+ rows.append(("note", "running... Ctrl+C stops it", block))
634
+ for item in block.view or []:
635
+ rows.extend(self.item_rows(item, block))
636
+ if block.code not in (None, 0):
637
+ rows.append(("err", f"exit {block.code} · {block.seconds:.2f}s", block))
638
+ elif block.command and not block.running:
639
+ rows.append(("note", f"{block.seconds:.2f}s", block))
640
+ rows.append(("gap", None, block))
641
+
642
+ if self.search is not None:
643
+ for i, match in enumerate(self.search_matches()[:6]):
644
+ marker = "▸ " if i == self.search_idx else " "
645
+ rows.append(("note", marker + match, None))
646
+ return rows
647
+
648
+ def item_rows(self, item, block):
649
+ out = []
650
+ kind = item.get("type")
651
+ if kind == "text":
652
+ for line in item["lines"][:MAX_OUT_LINES]:
653
+ out.append(("text", line, block))
654
+ elif kind == "kv":
655
+ for key, value in item["pairs"]:
656
+ out.append(("kv", (str(key), str(value)), block))
657
+ elif kind == "bars":
658
+ for label, pct, caption in item["rows"]:
659
+ out.append(("bar", (str(label), int(pct), str(caption)), block))
660
+ elif kind == "table":
661
+ bar_col = item.get("bar_col")
662
+ layout = views.table_layout(item["headers"], item["rows"], bar_col)
663
+ out.append(("cells", (item["headers"], layout, "muted", bar_col, True), block))
664
+ for i, row in enumerate(item["rows"]):
665
+ tone = item["tone"][i] if i < len(item["tone"]) else None
666
+ out.append(("cells", (row, layout, tone, bar_col, False), block))
667
+ return out
668
+
669
+ # ---- drawing -----------------------------------------------------------
670
+
671
+ def draw(self):
672
+ t = self.theme
673
+ self.screen.fill(t["bg"])
674
+ width, height = self.screen.get_size()
675
+ input_h = self.line_h + PAD * 2
676
+ bottom = height - input_h
677
+
678
+ rows = self.rows()
679
+ visible_count = max(1, (bottom - PAD) // self.line_h)
680
+ self.scroll = min(self.scroll, max(0, len(rows) - visible_count))
681
+ end = len(rows) - self.scroll
682
+ start = max(0, end - visible_count)
683
+ self.visible = rows[start:end]
684
+
685
+ y = PAD
686
+ for kind, payload, block in self.visible:
687
+ self.draw_row(kind, payload, y)
688
+ y += self.line_h
689
+
690
+ pygame.draw.line(self.screen, t["bar_bg"], (0, bottom), (width, bottom))
691
+ y = bottom + PAD
692
+ if self.pending is not None:
693
+ pieces = [("confirm y/N ❯ ", "warn")]
694
+ elif self.search is not None:
695
+ pieces = [("search ❯ ", "accent")]
696
+ else:
697
+ pieces = self.make_prompt()
698
+ x = self.draw_pieces(pieces, PAD, y)
699
+ shown = self.search if self.search is not None else self.input
700
+ cursor = "▌" if (pygame.time.get_ticks() // 500) % 2 == 0 else " "
701
+ self.text(shown + cursor, x, y, t["fg"])
702
+
703
+ if time.monotonic() < self.toast_until and self.toast_text:
704
+ x = width - PAD - self.char_w * len(self.toast_text)
705
+ self.text(self.toast_text, x, y, t["accent"])
706
+
707
+ def draw_row(self, kind, payload, y):
708
+ t = self.theme
709
+ if kind == "prompt":
710
+ pieces, command = payload
711
+ x = self.draw_pieces(pieces, PAD, y)
712
+ self.text(command, x, y, t["fg"])
713
+ elif kind == "text":
714
+ self.text(payload, PAD, y, t["fg"])
715
+ elif kind == "kv":
716
+ key, value = payload
717
+ self.text(key, PAD, y, t["muted"])
718
+ self.text(value, PAD + KEY_COLS * self.char_w, y, t["fg"])
719
+ elif kind == "bar":
720
+ label, pct, caption = payload
721
+ self.text(label, PAD, y, t["fg"])
722
+ bx = PAD + BAR_COLS * self.char_w
723
+ self.draw_bar(bx, y, pct, BAR_PX)
724
+ self.text(caption, bx + BAR_PX + 10, y, t["muted"])
725
+ elif kind == "cells":
726
+ cells, layout, tone, bar_col, is_header = payload
727
+ for i, (x_units, w_units) in enumerate(layout):
728
+ x = PAD + x_units * self.char_w
729
+ cell = str(cells[i]) if i < len(cells) else ""
730
+ if i == bar_col and not is_header:
731
+ self.draw_bar(x, y, parse_pct(cell), 12 * self.char_w)
732
+ self.text(cell, x + 13 * self.char_w, y, self.color(tone))
733
+ else:
734
+ color = self.color(tone) if not is_header else self.color("muted")
735
+ self.text(cell[: max(1, w_units - 2)], x, y, color)
736
+ elif kind == "err":
737
+ self.text(payload, PAD, y, t["warn"])
738
+ elif kind == "note":
739
+ self.text(payload, PAD, y, t["muted"])
740
+
741
+ def draw_pieces(self, pieces, x, y):
742
+ for text, key in pieces:
743
+ surf = self.font.render(text, True, self.color(key))
744
+ self.screen.blit(surf, (x, y))
745
+ x += self.char_w * len(text)
746
+ return x
747
+
748
+ def draw_bar(self, x, y, pct, width):
749
+ t = self.theme
750
+ h = max(6, self.line_h // 2 - 2)
751
+ by = y + (self.line_h - h) // 2
752
+ pct = max(0, min(100, pct))
753
+ pygame.draw.rect(self.screen, t["bar_bg"], (x, by, width, h), border_radius=3)
754
+ if pct:
755
+ color = t["warn"] if pct > 85 else t["accent"]
756
+ pygame.draw.rect(self.screen, color, (x, by, max(2, width * pct // 100), h), border_radius=3)
757
+
758
+ def text(self, value, x, y, color=None):
759
+ if color is None:
760
+ color = self.theme["fg"]
761
+ value = value.replace("\t", " ")
762
+ max_chars = (self.screen.get_width() - x - PAD) // self.char_w
763
+ if max_chars <= 0:
764
+ return
765
+ self.screen.blit(self.font.render(value[:max_chars], True, color), (x, y))