-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfiglet_studio.py
More file actions
663 lines (546 loc) · 22.8 KB
/
figlet_studio.py
File metadata and controls
663 lines (546 loc) · 22.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
#!/usr/bin/env python3
"""
Figlet Studio - A delightful TUI-based figlet studio
Because terminal art deserves a studio of its own.
"""
import os
import sys
import subprocess
import shutil
from pathlib import Path
from dataclasses import dataclass
from typing import Optional
from textual.app import App, ComposeResult
from textual.containers import Horizontal, Vertical
from textual.widgets import (
Header,
Footer,
Input,
TextArea,
ListView,
ListItem,
Label,
Static,
)
from textual.binding import Binding
from textual import on
from textual.reactive import reactive
from textual.color import Color
from pyperclip import paste, copy
# ═══════════════════════════════════════════════════════════════
# CHARM, WIT, AND COLOR PALETTES
# ═══════════════════════════════════════════════════════════════
WITTY_PREAMBLES = [
"✨ Welcome to Figlet Studio! Where ASCII dreams come true...",
"🎨 Your terminal is now an art studio. No beret required.",
"✏️ The Mona Lisa of ASCII awaits your brushstrokes...",
"🖼️ Creating magnificent text art, one blocky letter at a time...",
"✨ Warning: May cause excessive terminal envy in coworkers...",
"✨ Your words, but make them... blockier.",
"✨ Where text becomes texture and fonts become fun!",
"✨ ASCII art: the original pixel art, now in TUI form!",
]
FUN_RENDERS = [
"✨ Rendering your masterpiece...",
"🎨 Crafting character-by-character...",
"✏️ Font-forging in progress...",
"✨ Sprinkling ASCII dust on your words...",
"✨ Transforming mere text into ART...",
]
SUCCESS_COPIES = [
"✨ Copied to clipboard! Your clipboard is now ~25% more fabulous.",
"✨ Art delivered to clipboard. Use responsibly!",
"✨ Copied! Now go paste something wonderful.",
"✨ Clipboard enriched with ASCII excellence.",
"✨ Your art has been liberated to the clipboard!",
]
SUCCESS_SAVES = [
"💾 Saved to file! Your art is now immortalized on disk.",
"💾 File created! Future generations will thank you.",
"💾 Saved! Your masterpiece has been preserved for eternity.",
"💾 Written to disk! The art survives!",
]
ERROR_COPIES = [
"😅 Clipboard copy failed. Perhaps your clipboard is on strike?",
"😅 Couldn't copy. Maybe your clipboard is feeling shy?",
]
ERROR_SAVES = [
"😅 Save failed! The filesystem gods are not pleased.",
"😅 Couldn't save! File system said 'nah'.",
]
# ═══════════════════════════════════════════════════════════════
# FONT DISCOVERY
# ═══════════════════════════════════════════════════════════════
@dataclass
class FontInfo:
name: str
source: str # 'figlet' or 'toilet'
path: Path
class FontDiscoverer:
"""
Discovers figlet and toilet fonts on the system.
Because finding fonts is an adventure on every OS.
"""
# Common font locations by OS
FONT_PATHS = {
"darwin": [ # macOS
Path("/usr/local/share/figlet"),
Path("/opt/homebrew/share/figlet"),
Path("/usr/share/figlet"),
Path("~/Library/Fonts/figlet"),
Path("/usr/local/share/toilet"),
Path("/opt/homebrew/share/toilet"),
Path("/usr/share/toilet"),
],
"linux": [ # Linux
Path("/usr/share/figlet"),
Path("/usr/local/share/figlet"),
Path("~/.local/share/figlet"),
Path("/usr/share/toilet"),
Path("/usr/local/share/toilet"),
Path("~/.local/share/toilet"),
],
"win32": [ # Windows (WSL paths)
Path("/mnt/c/Program Files/figlet"),
Path("/mnt/c/figlet"),
Path("/usr/share/figlet"),
Path("/usr/share/toilet"),
],
}
def __init__(self):
self.platform = sys.platform
self.figlet_available = self._check_figlet()
self.toilet_available = self._check_toilet()
def _check_command(self, cmd: str) -> bool:
"""Check if a command is available."""
return shutil.which(cmd) is not None
def _check_figlet(self) -> bool:
return self._check_command("figlet")
def _check_toilet(self) -> bool:
return self._check_command("toilet")
def get_font_paths(self) -> list[Path]:
"""Get all possible font directories for current platform."""
paths = []
platform_key = "darwin" if self.platform == "darwin" else "linux" if self.platform.startswith("linux") else "win32"
for base_path in self.FONT_PATHS.get(platform_key, []):
expanded = base_path.expanduser()
if expanded.exists() and expanded.is_dir():
paths.append(expanded)
return paths
def discover_fonts(self) -> list[FontInfo]:
"""Discover all available figlet and toilet fonts."""
fonts = []
for font_dir in self.get_font_paths():
# Check for figlet fonts (including subdirectories)
if self.figlet_available:
figlet_dir = font_dir
if figlet_dir.exists():
for font_file in sorted(figlet_dir.rglob("*.flf")):
# Get just the filename without extension for figlet
font_name = font_file.name.rsplit('.', 1)[0]
fonts.append(FontInfo(
name=font_name,
source="figlet",
path=font_file
))
# Check for toilet fonts
if self.toilet_available:
toilet_fonts_dir = font_dir / "fonts"
if toilet_fonts_dir.exists():
for font_file in sorted(toilet_fonts_dir.rglob("*.flf")):
font_name = font_file.name.rsplit('.', 1)[0]
fonts.append(FontInfo(
name=font_name,
source="toilet",
path=font_file
))
for font_file in sorted(toilet_fonts_dir.rglob("*.tlf")):
font_name = font_file.name.rsplit('.', 1)[0]
fonts.append(FontInfo(
name=font_name,
source="toilet",
path=font_file
))
return fonts
# ═══════════════════════════════════════════════════════════════
# FIGLET RENDERER
# ═══════════════════════════════════════════════════════════════
class FigletRenderer:
"""
Renders text using figlet or toilet.
The artistic engine behind the studio.
"""
def __init__(self):
self.discoverer = FontDiscoverer()
self.fonts = self.discoverer.discover_fonts()
self.current_font_path = str(self.fonts[0].path) if self.fonts else "standard"
self.current_source = self.fonts[0].source if self.fonts else "figlet"
self.width = 80
def render(self, text: str) -> tuple[str, str]:
"""
Render text with current font.
Returns (output, error_message)
"""
if not self.discoverer.figlet_available and not self.discoverer.toilet_available:
return "", "Neither figlet nor toilet is installed!"
if not text.strip():
return "", ""
try:
# Resolve the font path to handle any symlinks
font_path = Path(self.current_font_path).resolve()
if self.current_source == "toilet" and self.discoverer.toilet_available:
cmd = ["toilet", "-f", str(font_path), "-w", str(self.width), text]
elif self.discoverer.figlet_available:
cmd = ["figlet", "-f", str(font_path), "-w", str(self.width), text]
else:
# Fallback
cmd = ["figlet", "-f", str(font_path), "-w", str(self.width), text]
result = subprocess.run(
cmd,
capture_output=True,
encoding="utf-8",
errors="replace",
timeout=2
)
if result.returncode == 0:
return result.stdout, ""
else:
return text, f"Font error: {result.stderr.strip() or 'Unknown error'}"
except subprocess.TimeoutExpired:
return text, "Rendering timed out! Try a shorter text."
except Exception as e:
return text, f"Render error: {str(e)}"
def set_font(self, font_name: str, source: str, font_path: Path) -> bool:
"""Set the current font. Returns True if successful."""
self.current_font_path = str(font_path)
self.current_source = source
return True
# ═══════════════════════════════════════════════════════════════
# CUSTOM WIDGETS WITH PIZZAZZ
# ═══════════════════════════════════════════════════════════════
class ColorfulFooter(Footer):
"""A footer with more personality."""
def make_key_text(self, key: str, name: str = "", hint: str = "") -> str:
"""Create colorful key bindings display."""
key_text = f"[bold cyan]{key}[/bold cyan]"
if name:
name_text = f"[italic yellow]{name}[/italic yellow]"
return f"{key_text} {name_text}"
return key_text
def render(self):
"""Render the footer with colorful bindings."""
self.key_text = self.make_key_text
return super().render()
class FigletPreview(TextArea):
"""The main preview area for figlet output."""
default_css = """
FigletPreview {
background: $panel;
color: $primary;
border: double $primary;
padding: 1;
}
FigletPreview:focus {
border: double $accent;
}
"""
def __init__(self, **kwargs):
super().__init__(read_only=True, **kwargs)
def update_render(self, text: str, color: str = "primary"):
"""Update the preview with new rendered text."""
self.clear()
self.load_text(text)
self.border_subtitle = f"[{color}]✨ PREVIEW ✨[/]"
class ColorfulFontList(ListView):
"""A colorful font list widget."""
def __init__(self, fonts: list[FontInfo], **kwargs):
self.fonts = fonts
items = []
# Color palette for font items
colors = [
"cyan", "magenta", "yellow", "green", "blue", "red",
"bright_cyan", "bright_magenta", "bright_yellow",
]
for i, font in enumerate(fonts):
color = colors[i % len(colors)]
source_icon = "🎭" if font.source == "toilet" else "✏️"
label_text = f"[{color}]{source_icon} {font.name}[/]"
items.append(ListItem(Label(label_text)))
super().__init__(*items, **kwargs)
class StatusBar(Static):
"""A status bar with witty messages."""
message = reactive("")
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.message = WITTY_PREAMBLES[0]
def watch_message(self, old: str, new: str) -> None:
"""Update display when message changes."""
self.update(f"[bold yellow]✦[/] [italic]{new}[/]")
# ═══════════════════════════════════════════════════════════════
# MAIN APPLICATION
# ═══════════════════════════════════════════════════════════════
class FigletStudioApp(App):
"""
The main Figlet Studio application.
Where ASCII dreams become terminal reality.
"""
CSS = """
Screen {
background: $background;
}
Header {
background: $primary 80%;
text-style: bold;
}
#main_container {
height: 1fr;
}
#left_panel {
width: 2fr;
height: 100%;
}
#right_panel {
width: 1fr;
height: 100%;
border: double $accent;
background: $panel;
}
#preview_container {
height: 3fr;
padding: 0 1 1 1;
}
#input_container {
height: 1fr;
padding: 0 1 1 1;
}
FigletPreview {
height: 100%;
}
Input {
width: 100%;
background: $panel;
color: $text;
border: solid $accent;
padding: 1;
margin: 1 0;
text-style: bold;
}
Input:focus {
border: double $success;
background: $boost;
color: $text;
}
ColorfulFontList {
height: 1fr;
scrollbar-size: 1 2;
}
#font_list_header {
height: 3;
content-align: center middle;
text-style: bold;
background: $primary 80%;
border-bottom: solid $accent;
}
#status_bar {
dock: top;
height: 1;
background: $surface;
border-top: solid $accent;
padding: 0 1;
content-align: left middle;
}
#title_label {
text-style: bold;
text-align: center;
}
"""
BINDINGS = [
Binding("space", "copy_to_clipboard", "Copy to Clipboard"),
Binding("s", "save_to_file", "Save to File"),
Binding("q", "quit", "Quit", show=True),
Binding("ctrl+c", "quit", "Quit", show=False),
Binding("tab", "focus_next", "Next", show=True),
Binding("shift+tab", "focus_previous", "Previous", show=True),
]
def __init__(self):
# Check for figlet first
if not shutil.which("figlet") and not shutil.which("toilet"):
self._print_error_and_exit()
# We never actually get here due to sys.exit()
self.renderer = FigletRenderer()
self.current_text = "Figlet Studio"
# Handle no fonts case
if not self.renderer.fonts:
print("\n[yellow]⚠️ Warning: No fonts found![/yellow]")
print("This is unusual. You may have a custom figlet installation.")
print("Proceeding with default font...\n")
super().__init__()
def _print_error_and_exit(self):
"""Print a colorful, helpful error message and exit."""
from rich.console import Console
from rich.panel import Panel
from rich.text import Text
console = Console()
title = Text("✨ FIGLET STUDIO ✨", style="bold magenta")
subtitle = Text("The Delightful TUI ASCII Art Studio", style="italic cyan")
error_msg = Text()
error_msg.append("😢 Oh no! ", style="bold red")
error_msg.append("figlet", style="bold yellow")
error_msg.append(" is not installed on your system!\n\n", style="red")
install_title = Text("📦 Please install figlet using your package manager:\n\n", style="bold cyan")
install_cmds = Text()
install_cmds.append("macOS (Homebrew):\n", style="bold yellow")
install_cmds.append(" brew install figlet toilet\n\n", style="green")
install_cmds.append("macOS (MacPorts):\n", style="bold yellow")
install_cmds.append(" sudo port install figlet toilet\n\n", style="green")
install_cmds.append("Ubuntu/Debian:\n", style="bold yellow")
install_cmds.append(" sudo apt install figlet toilet\n\n", style="green")
install_cmds.append("Fedora/RHEL:\n", style="bold yellow")
install_cmds.append(" sudo dnf install figlet toilet\n\n", style="green")
install_cmds.append("Arch Linux:\n", style="bold yellow")
install_cmds.append(" sudo pacman -S figlet toilet\n\n", style="green")
install_cmds.append("Windows (WSL):\n", style="bold yellow")
install_cmds.append(" sudo apt install figlet toilet\n\n", style="green")
closing = Text()
closing.append("After installation, run ", style="dim")
closing.append("figlet-studio", style="bold green")
closing.append(" again!", style="dim")
panel = Panel.fit(
error_msg + install_title + install_cmds + closing,
title=title,
title_align="center",
border_style="bright_magenta",
padding=(1, 2),
)
console.print("\n")
console.print(subtitle, justify="center")
console.print("\n")
console.print(panel)
console.print("\n")
sys.exit(1)
def compose(self) -> ComposeResult:
"""Compose the UI."""
# Header with title
yield Header(show_clock=True)
# Status bar
yield StatusBar(id="status_bar")
# Main container
with Horizontal(id="main_container"):
# Left panel: preview + input
with Vertical(id="left_panel"):
with Vertical(id="preview_container"):
yield FigletPreview(id="preview")
with Vertical(id="input_container"):
yield Input(
placeholder="Type your text here for instant ASCII magic...",
value="Figlet Studio",
id="text_input"
)
yield Static(
"[dim]Press [bold cyan]Space[/] to copy | Press [bold cyan]S[/] to save | Press [bold cyan]Q[/] to quit[/]",
id="help_text"
)
# Right panel: font list
with Vertical(id="right_panel"):
yield Static(
"[bold magenta]✨ FONT GALLERY ✨[/]\n[dim]Scroll to select a font[/]",
id="font_list_header"
)
if self.renderer.fonts:
yield ColorfulFontList(self.renderer.fonts, id="font_list")
else:
yield Static("[yellow]⚠️ No fonts found![/yellow]", id="font_list")
yield Footer()
def on_mount(self) -> None:
"""Initialize the app on mount."""
# Focus the input
input_widget = self.query_one("#text_input", Input)
input_widget.focus()
# Initial render
self._update_preview()
def on_input_changed(self, event: Input.Changed) -> None:
"""Handle text input changes."""
if event.input.id == "text_input":
self.current_text = event.value or " "
self._update_preview()
@on(ListView.Selected, "ColorfulFontList")
def on_font_selected(self, event: ListView.Selected) -> None:
"""Handle font selection."""
if self.renderer.fonts and event.item is not None:
# Find the index by searching children of the target (the ListView)
font_list = self.query_one("#font_list", ColorfulFontList)
index = list(font_list.children).index(event.item)
if 0 <= index < len(self.renderer.fonts):
font = self.renderer.fonts[index]
self.renderer.set_font(font.name, font.source, font.path)
self._update_preview()
self._set_status(f"Font changed to [bold cyan]{font.name}[/] ([dim]{font.source}[/])")
def _update_preview(self) -> None:
"""Update the preview with current settings."""
preview = self.query_one("#preview", FigletPreview)
if not self.current_text.strip():
preview.clear()
return
rendered, error = self.renderer.render(self.current_text)
if error:
preview.load_text(rendered + f"\n\n[red]⚠️ {error}[/]")
else:
preview.load_text(rendered)
def _set_status(self, message: str) -> None:
"""Update the status bar with a message."""
status_bar = self.query_one("#status_bar", StatusBar)
import random
if "copied" in message.lower():
message = random.choice(SUCCESS_COPIES)
elif "saved" in message.lower():
message = random.choice(SUCCESS_SAVES)
status_bar.message = message
def action_copy_to_clipboard(self) -> None:
"""Copy the current render to clipboard."""
preview = self.query_one("#preview", FigletPreview)
text = preview.text
try:
copy(text)
import random
self._set_status(random.choice(SUCCESS_COPIES))
except Exception as e:
import random
self._set_status(random.choice(ERROR_COPIES) + f" ({str(e)})")
def action_save_to_file(self) -> None:
"""Save the current render to a file."""
preview = self.query_one("#preview", FigletPreview)
text = preview.text
# Create output directory if it doesn't exist
output_dir = Path.home() / ".figlet-studio"
output_dir.mkdir(exist_ok=True)
# Generate filename
import datetime
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
safe_text = "".join(c for c in self.current_text[:20] if c.isalnum() or c in (' ', '-', '_')).strip()
safe_text = safe_text.replace(' ', '_') or "output"
filename = f"{safe_text}_{timestamp}.txt"
filepath = output_dir / filename
try:
filepath.write_text(text)
import random
self._set_status(f"{random.choice(SUCCESS_SAVES)} Saved to: [dim]{filepath}[/]")
except Exception as e:
import random
self._set_status(f"{random.choice(ERROR_SAVES)} ({str(e)})")
# ═══════════════════════════════════════════════════════════════
# ENTRY POINT
# ═══════════════════════════════════════════════════════════════
def main():
"""Main entry point."""
import random
print(random.choice(WITTY_PREAMBLES))
print("[dim]Initializing your ASCII art studio...[/dim]")
print("")
try:
app = FigletStudioApp()
app.run()
except KeyboardInterrupt:
print("\n\n[yellow]👋 Thanks for using Figlet Studio! Keep making ASCII magic![/yellow]")
sys.exit(0)
if __name__ == "__main__":
main()