### Quick Start Example Source: https://pyratatui.github.io/pyratatui/reference/image_widget Example demonstrating how to use ImagePicker and ImageWidget to display an image in the terminal, prioritizing the best available protocol. ```APIDOC ## Quick Start (Best Quality) Use `from_query()` so the picker can query the terminal for the best available protocol and the actual cell pixel size. This performs terminal I/O, so call it after entering `Terminal()` and before you start reading events. ```python from pyratatui import ImagePicker, ImageWidget, Terminal with Terminal() as term: try: picker = ImagePicker.from_query() except RuntimeError: picker = ImagePicker.halfblocks() # Fallback to halfblocks if query fails state = picker.load("photo.png") widget = ImageWidget() def ui(frame): frame.render_stateful_image(widget, frame.area, state) term.draw(ui) ``` ``` -------------------------------- ### BarGraph Quick Start Example Source: https://pyratatui.github.io/pyratatui/reference/bar_graph A basic example demonstrating how to initialize and render a BarGraph widget. ```APIDOC ## Quick Start ### Description This example shows a minimal setup to create and display a BarGraph. ### Method ```python from pyratatui import BarGraph, BarGraphStyle, BarColorMode, Terminal, Layout, Constraint with Terminal() as term: def ui(frame): graph = ( BarGraph([0.2, 0.8, 0.5, 0.9, 0.3, 0.6]) .bar_style(BarGraphStyle.Braille) .color_mode(BarColorMode.VerticalGradient) .gradient("turbo") ) frame.render_widget(graph, frame.area) term.draw(ui) ``` ### Parameters None ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Use run_app_async Helper Source: https://pyratatui.github.io/pyratatui/tutorial/async_updates This example shows the usage of the `run_app_async` convenience helper for simple asynchronous Pyratatui applications. It handles terminal setup, event loop, and quitting. ```python from pyratatui import run_app_async async def my_ui(frame): frame.render_widget( Paragraph.from_string("Simple async app!"), frame.area, ) asyncio.run(run_app_async(my_ui, fps=30)) ``` -------------------------------- ### Install pyratatui Source: https://pyratatui.github.io/pyratatui/tutorial/quickstart Install the library using pip. ```bash pip install pyratatui ``` -------------------------------- ### Buffer usage example Source: https://pyratatui.github.io/pyratatui/reference/buffer Comprehensive example demonstrating buffer creation, writing, reading, and resetting. ```python from pyratatui import Buffer, Rect, Style, Color # Create an 80Γ—24 buffer buf = Buffer(Rect(0, 0, 80, 24)) # Write content buf.set_string(0, 0, "Header", Style().fg(Color.cyan()).bold()) buf.set_string(0, 1, "Body text", Style().fg(Color.white())) # Read back header = buf.get_string(0, 0, 6) assert header == "Header" # Clear and reuse buf.reset() ``` -------------------------------- ### Set up a virtual environment and install Pyratatui Source: https://pyratatui.github.io/pyratatui/installation Recommended approach for managing dependencies. This creates a virtual environment, activates it, and then installs Pyratatui. ```bash python -m venv .venv source .venv/bin/activate # Linux / macOS .venv\Scripts\activate # Windows PowerShell pip install pyratatui ``` -------------------------------- ### Create and Render a Bar Graph Source: https://pyratatui.github.io/pyratatui/reference/bar_graph Quick start example demonstrating how to create a BarGraph with sample data, apply styling and color modes, and render it to the terminal. ```python from pyratatui import BarGraph, BarGraphStyle, BarColorMode, Terminal, Layout, Constraint with Terminal() as term: def ui(frame): graph = ( BarGraph([0.2, 0.8, 0.5, 0.9, 0.3, 0.6]) .bar_style(BarGraphStyle.Braille) .color_mode(BarColorMode.VerticalGradient) .gradient("turbo") ) frame.render_widget(graph, frame.area) term.draw(ui) ``` -------------------------------- ### Install Rust toolchain for building from source Source: https://pyratatui.github.io/pyratatui/installation Installs the Rust toolchain using rustup. This is a prerequisite for building Pyratatui from source. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source "$HOME/.cargo/env" rustup update stable ``` -------------------------------- ### Buffer Usage Example Source: https://pyratatui.github.io/pyratatui/reference/buffer A practical example demonstrating the creation and manipulation of a Buffer object. ```APIDOC ## Usage Example ### Description Demonstrates creating an 80x24 buffer, writing content with styles, reading content back, and then clearing the buffer. ### Code Example ```python from pyratatui import Buffer, Rect, Style, Color # Create an 80x24 buffer buf = Buffer(Rect(0, 0, 80, 24)) # Write content buf.set_string(0, 0, "Header", Style().fg(Color.cyan()).bold()) buf.set_string(0, 1, "Body text", Style().fg(Color.white())) # Read back header = buf.get_string(0, 0, 6) assert header == "Header" # Clear and reuse buf.reset() ``` ``` -------------------------------- ### Style & Text Cookbook Examples Source: https://pyratatui.github.io/pyratatui/reference/style Practical examples demonstrating how to use Span, Line, and Text for common formatting tasks. ```APIDOC ## Style & Text Cookbook ### Colorize a word in a sentence ```python line = Line([ Span("Server is "), Span("ONLINE", Style().fg(Color.green()).bold()), Span(" β€” uptime 24h"), ]) ``` ### Mixed Alignment in a Multi-Line Block ```python text = Text([ Line.from_string("Centered title").centered(), Line.from_string(""), Line.from_string("Left aligned body text"), Line.from_string("Right aligned note").right_aligned(), ]) ``` ### Styled Table of Key/Value Pairs ```python def kv_line(key: str, value: str, value_color=None): return Line([ Span(f"{key:<12}", Style().fg(Color.gray())), Span(value, Style().fg(value_color or Color.white())), ]) text = Text([ kv_line("CPU", "72%", Color.yellow()), kv_line("Memory", "4.2 GB", Color.cyan()), kv_line("Requests", "1,024,000", Color.green()), kv_line("Errors", "0", Color.green()), ]) ``` ### Building Text Progressively ```python text = Text() for message in log_entries: color = Color.red() if "ERROR" in message else Color.gray() text.push_line(Line([Span(message, Style().fg(color))])) ``` ``` -------------------------------- ### One-Shot Sweep-In Animation on Startup Source: https://pyratatui.github.io/pyratatui/tutorial/tachyonfx_effects This example demonstrates a one-shot sweep animation that plays once when the application starts. It uses Effect.sweep_in with specified motion, gradient, color, duration, and interpolation. The UI then runs normally. ```python import time from pyratatui import ( Terminal, Paragraph, Block, Style, Color, Effect, EffectManager, Motion, Interpolation, ) mgr = EffectManager() # One-shot sweep: play once and stop mgr.add(Effect.sweep_in(Motion.LeftToRight, sweep_span=20, gradient_len=5, color=Color.black(), duration_ms=800, interpolation=Interpolation.QuadOut)) last = time.monotonic() with Terminal() as term: term.hide_cursor() while True: now = time.monotonic() ms = int((now - last) * 1000) last = now def ui(frame, _mgr=mgr, _ms=ms): area = frame.area frame.render_widget( Paragraph.from_string("Welcome to my app!\n\nLoading complete.") .block(Block().bordered().title(" Startup ")) .style(Style().fg(Color.cyan())), area, ) if _mgr.has_active(): frame.apply_effect_manager(_mgr, _ms, area) term.draw(ui) ev = term.poll_event(timeout_ms=16) if ev and ev.code == "q": break term.show_cursor() ``` -------------------------------- ### Install Pyratatui using pip Source: https://pyratatui.github.io/pyratatui/installation Recommended installation method using pip for pre-built wheels. Ensure you have Python 3.10+ and a compatible operating system. ```bash pip install pyratatui ``` -------------------------------- ### Clone and Install Pyratatui for Development Source: https://pyratatui.github.io/pyratatui/build/build_scripts Clone the repository, set up a virtual environment, install Maturin, and then build and install the package in editable mode for development. Use 'maturin develop' for debug builds and 'maturin develop --release' for optimized builds. ```bash # 1. Clone the repo git clone https://github.com/pyratatui/pyratatui.git cd pyratatui # 2. Create a virtual environment python -m venv .venv source .venv/bin/activate # Linux/macOS .venv\Scripts\activate # Windows # 3. Install build dependencies pip install maturin # 4. Build and install in editable mode maturin develop # debug build (fast compile) maturin develop --release # optimized build (recommended) ``` -------------------------------- ### Install Pyratatui in Docker Source: https://pyratatui.github.io/pyratatui/faq Dockerfile configuration to install Rust and Pyratatui. ```dockerfile FROM python:3.12-slim # Install Rust (only needed if building from source) RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y ENV PATH="/root/.cargo/bin:${PATH}" RUN pip install pyratatui ``` -------------------------------- ### Build TextPrompt Source: https://pyratatui.github.io/pyratatui/reference/prompts Example of using the builder pattern to configure a prompt. ```python prompt = TextPrompt("Input: ").with_render_style(TextRenderStyle.Password) ``` -------------------------------- ### Hello World with Pyratatui Source: https://pyratatui.github.io/pyratatui/examples/minimal_examples A basic "Hello World" example demonstrating how to initialize a terminal, render a paragraph with styling, and handle basic input for quitting. ```Python # examples/01_hello_world.py from pyratatui import Terminal, Paragraph, Block, Style, Color with Terminal() as term: while True: def ui(frame): frame.render_widget( Paragraph.from_string("Hello, pyratatui! πŸ€ Press q to quit.") .block(Block().bordered().title("Hello World")) .style(Style().fg(Color.cyan())), frame.area, ) term.draw(ui) ev = term.poll_event(timeout_ms=100) if ev and ev.code == "q": break ``` -------------------------------- ### Run interactive calendar example Source: https://pyratatui.github.io/pyratatui/reference/calendar Command to execute the provided interactive calendar demonstration script. ```bash python examples/25_calendar.py ``` -------------------------------- ### Install Pyratatui via pip Source: https://pyratatui.github.io/pyratatui/faq Commands to reinstall or verify the Pyratatui installation. ```bash pip install --force-reinstall pyratatui ``` ```bash maturin develop --release ``` ```bash python --version ``` ```bash pip show pyratatui ``` -------------------------------- ### Complete Example: Interactive QR Code Source: https://pyratatui.github.io/pyratatui/reference/qrcode An advanced example demonstrating an interactive QR code display. It allows cycling through URLs, inverting colors, and quitting. The QR code is rendered alongside help text. ```python from pyratatui import ( Block, Color, Constraint, Direction, Layout, Paragraph, QrCodeWidget, QrColors, Style, Terminal, ) URLS = ["https://ratatui.rs", "https://pyo3.rs"] url_idx = 0 color_scheme = QrColors.Inverted with Terminal() as term: while True: url = URLS[url_idx % len(URLS)] qr = QrCodeWidget(url).colors(color_scheme) def ui(frame, _qr=qr, _url=url): chunks = ( Layout() .direction(Direction.Horizontal) .constraints([Constraint.length(50), Constraint.min(0)]) .split(frame.area) ) qr_block = Block().bordered().title(" QR Code ") qr_inner = qr_block.inner(chunks[0]) frame.render_widget(qr_block, chunks[0]) frame.render_qrcode(_qr, qr_inner) help = Paragraph.from_string(f"\n URL: {_url}\n\n n=next i=invert q=quit") frame.render_widget(help.block(Block().bordered()), chunks[1]) term.draw(ui) ev = term.poll_event(timeout_ms=200) if ev: if ev.code in ("q", "Esc"): break elif ev.code == "n": url_idx += 1 elif ev.code == "i": color_scheme = ( QrColors.Default if color_scheme == QrColors.Inverted else QrColors.Inverted ) ``` -------------------------------- ### Complete Popup Example Source: https://pyratatui.github.io/pyratatui/reference/popups A comprehensive example demonstrating the integration of Popup, PopupState, and KnownSizeWrapper for creating a scrollable and draggable popup within a TUI application. ```APIDOC ## Complete Example ```python import time from pyratatui import ( Color, KnownSizeWrapper, Paragraph, Popup, PopupState, Style, Terminal, ) lines = [f" {i:03d}. Item number {i}" for i in range(1, 31)] wrapper = KnownSizeWrapper(lines, width=40, height=8) state = PopupState() bg = Paragraph.from_string("background").style(Style().fg(Color.dark_gray())) popup = ( Popup(wrapper) .title(" Scrollable & Draggable ") .style(Style().fg(Color.white()).bg(Color.dark_gray())) ) with Terminal() as term: while True: def ui(frame, _p=popup, _s=state): frame.render_widget(bg, frame.area) frame.render_stateful_popup(_p, frame.area, _s) term.draw(ui) ev = term.poll_event(timeout_ms=50) if ev is None: continue if ev.code in ("q", "Esc"): break elif ev.code == "Up": state.move_up(1) elif ev.code == "Down": state.move_down(1) elif ev.code == "Left": state.move_left(1) elif ev.code == "Right": state.move_right(1) elif ev.code == "r": state.reset() ``` ``` -------------------------------- ### Progress Gauge Example Source: https://pyratatui.github.io/pyratatui/examples/minimal_examples Illustrates a dynamic progress gauge using the `Gauge` widget. The example updates the gauge's ratio and label over time and handles quitting. ```Python # examples/05_progress_bar.py import time from pyratatui import Block, Gauge, Style, Color, Terminal with Terminal() as term: for step in range(101): def ui(frame, s=step): frame.render_widget( Gauge() .block(Block().bordered().title(" Progress ")) .ratio(s / 100) .label(f"{s}%") .gauge_style(Style().fg(Color.green())), frame.area, ) term.draw(ui) ev = term.poll_event(timeout_ms=50) if ev and ev.code == "q": break time.sleep(0.05) ``` -------------------------------- ### Offline Installation Commands Source: https://pyratatui.github.io/pyratatui/build/packaging Downloads wheels for offline distribution and installs them without dependencies. ```bash # Download wheel file and install offline pip download pyratatui --no-deps -d ./wheels/ pip install --no-index --find-links=./wheels/ pyratatui ``` -------------------------------- ### Throbber Widget Example Source: https://pyratatui.github.io/pyratatui/reference/throbber_widget A complete example demonstrating how to render a Throbber widget within a terminal application loop. ```python from pyratatui import Block, Color, Style, Terminal, Throbber th = Throbber("Syncing...") th.set_set("clock") th.set_throbber_style(Style().fg(Color.cyan()).bold()) with Terminal() as term: while True: def ui(frame): block = Block().bordered().title(" Throbber ") frame.render_widget(block, frame.area) frame.render_widget(th, block.inner(frame.area)) term.draw(ui) ev = term.poll_event(timeout_ms=80) if ev and ev.code == "q": break ``` -------------------------------- ### Execute a complete ScrollView example Source: https://pyratatui.github.io/pyratatui/reference/scrollview A simplified implementation of a scrollable view with basic navigation controls. ```python lines = [f" {i:03d}: " + "data " * 10 for i in range(200)] state = ScrollViewState() with Terminal() as term: while True: sv = ScrollView.from_lines(lines, content_width=100) term.draw(lambda frame: frame.render_stateful_scrollview(sv, frame.area, state)) ev = term.poll_event(timeout_ms=50) if ev: if ev.code == "Down": state.scroll_down(1) if ev.code == "Up": state.scroll_up(1) if ev.code == "q": break ``` -------------------------------- ### Verify Type Stubs Installation Source: https://pyratatui.github.io/pyratatui/build/packaging Checks that .pyi files are correctly included in the installed package directory. ```python python -c "import pyratatui; import pathlib; \ p = pathlib.Path(pyratatui.__file__).parent; \ print(list(p.glob('*.pyi')))" ``` -------------------------------- ### Configure Complex Block Source: https://pyratatui.github.io/pyratatui/reference/widgets Example of a fully configured Block with title, style, and padding. ```python from pyratatui import Block, BorderType, Style, Color block = (Block() .title("Service Monitor") .title_alignment("center") .title_style(Style().fg(Color.cyan()).bold()) .bordered() .border_type(BorderType.Rounded) .border_style(Style().fg(Color.dark_gray())) .style(Style().bg(Color.black())) .padding(left=1, right=1)) ``` -------------------------------- ### Initialize and Configure TuiLoggerWidget Source: https://pyratatui.github.io/pyratatui/reference/logger Setup the logger backend and configure the widget appearance before rendering. ```python from pyratatui import init_logger, log_message, TuiLoggerWidget, TuiWidgetState, Block, Style, Color # Call once at startup init_logger("debug") widget = ( TuiLoggerWidget() .block(Block().bordered().title(" Logs ")) .error_style(Style().fg(Color.red()).bold()) .warn_style(Style().fg(Color.yellow())) .info_style(Style().fg(Color.green())) ) state = TuiWidgetState() # In render loop: # frame.render_logger(widget, area, state) # To emit log messages: log_message("info", "Application started") log_message("warn", "Low memory") ``` -------------------------------- ### Basic Terminal UI Setup Source: https://pyratatui.github.io/pyratatui Initializes a terminal session and renders a simple paragraph widget within a bordered block. ```python from pyratatui import Terminal, Paragraph, Block, Style, Color with Terminal() as term: while True: def ui(frame): frame.render_widget( Paragraph.from_string("Hello, pyratatui! πŸ€ Press q to quit.") .block(Block().bordered().title("Hello World")) .style(Style().fg(Color.cyan())), frame.area, ) term.draw(ui) ev = term.poll_event(timeout_ms=100) if ev and ev.code == "q": break ``` -------------------------------- ### Create and Style a Popup Source: https://pyratatui.github.io/pyratatui/reference/popups Instantiate a Popup with content, set its title, and apply styling. This example shows stateless rendering. ```python from pyratatui import Popup, Style, Color popup = ( Popup("Press any key to exit.") .title(" Demo Popup ") .style(Style().fg(Color.white()).bg(Color.blue())) ) # Stateless rendering (always centered, no state needed): frame.render_popup(popup, frame.area) ``` -------------------------------- ### Configure password masking Source: https://pyratatui.github.io/pyratatui/reference/prompts Examples of creating a password-masked prompt using direct instantiation or the builder pattern. ```python # Create a password-masked prompt prompt = TextPrompt("Token: ", TextRenderStyle.Password) # or via builder: prompt = TextPrompt("Token: ").with_render_style(TextRenderStyle.Password) ``` -------------------------------- ### Implement a basic text prompt Source: https://pyratatui.github.io/pyratatui/reference/prompts A complete example showing the lifecycle of a text prompt using a stateful model within a terminal draw loop. ```python from pyratatui import Terminal, TextPrompt, TextState state = TextState() state.focus() with Terminal() as term: term.hide_cursor() while state.is_pending(): def ui(frame, _s=state): frame.render_text_prompt( TextPrompt("Name: "), frame.area, _s, ) term.draw(ui) ev = term.poll_event(timeout_ms=50) if ev: state.handle_key(ev) if state.is_complete(): print(f"Hello, {state.value()}!") ``` -------------------------------- ### Verify Pyratatui installation Source: https://pyratatui.github.io/pyratatui/installation Checks the installed versions of Pyratatui and its Ratatui backend. Ensure these match expected values. ```python import pyratatui print(pyratatui.__version__) # "0.2.7" print(pyratatui.__ratatui_version__) # "0.30" ``` -------------------------------- ### Implement an interactive calendar Source: https://pyratatui.github.io/pyratatui/examples/advanced_examples This example demonstrates how to use the Monthly widget along with a CalendarEventStore to render a calendar with custom date styling and keyboard-based navigation. ```python """ examples/25_calendar.py Controls: ←/β†’ Previous / next month ↑/↓ Previous / next year t Jump to today q Quit """ from __future__ import annotations import calendar as _cal from datetime import date as _pydate from pyratatui import ( Block, CalendarDate, CalendarEventStore, Color, Constraint, Direction, Layout, Line, Monthly, Paragraph, Span, Style, Terminal, Text, ) _today = _pydate.today() _year = _today.year _month = _today.month _MONTHS = ["", "January","February","March","April","May","June", "July","August","September","October","November","December"] def make_store(year, month): store = CalendarEventStore() if year == _today.year and month == _today.month: store.add_today(Style().fg(Color.green()).bold()) _, days = _cal.monthrange(year, month) for day in range(1, days + 1): if _cal.weekday(year, month, day) >= 5: store.add(CalendarDate.from_ymd(year, month, day), Style().fg(Color.yellow()).dim()) store.add(CalendarDate.from_ymd(year, month, 1), Style().fg(Color.cyan()).bold()) if days >= 15: store.add(CalendarDate.from_ymd(year, month, 15), Style().fg(Color.magenta()).bold()) return store def ui(frame): outer = (Layout().direction(Direction.Vertical) .constraints([Constraint.length(3), Constraint.min(1), Constraint.length(3)]) .split(frame.area)) frame.render_widget( Paragraph.from_string(f" {_MONTHS[_month]} {_year}") .block(Block().bordered().title(" Calendar ")) .centered().style(Style().fg(Color.cyan()).bold()), outer[0]) body = (Layout().direction(Direction.Horizontal) .constraints([Constraint.length(30), Constraint.fill(1)]) .split(outer[1])) frame.render_widget( Monthly(CalendarDate.from_ymd(_year, _month, 1), make_store(_year, _month)) .block(Block().bordered().title(" Monthly ")) .show_month_header(Style().bold().fg(Color.cyan())) .show_weekdays_header(Style().italic().fg(Color.light_blue())) .show_surrounding(Style().dim()) .default_style(Style().fg(Color.white())), body[0]) legend = Text([ Line([Span("Legend:", Style().bold())]), Line([]), Line([Span(" today", Style().fg(Color.green()).bold())]), Line([Span(" weekend", Style().fg(Color.yellow()).dim())]), Line([Span(" 1st", Style().fg(Color.cyan()).bold())]), Line([Span(" 15th", Style().fg(Color.magenta()).bold())]), Line([]), Line([Span(f"Today: {_today}", Style().dim())]), ]) frame.render_widget( Paragraph(legend).block(Block().bordered().title(" Legend ")), body[1]) frame.render_widget( Paragraph.from_string(" ←/β†’ month ↑/↓ year t today q quit") .block(Block().bordered()).style(Style().fg(Color.dark_gray())), outer[2]) def main(): global _year, _month with Terminal() as term: while True: term.draw(ui) ev = term.poll_event(timeout_ms=200) if not ev: continue if ev.code == "q": break elif ev.code == "Left": _month -= 1 if _month < 1: _month = 12; _year -= 1 elif ev.code == "Right": _month += 1 if _month > 12: _month = 1; _year += 1 elif ev.code == "Up": _year += 1 elif ev.code == "Down": _year -= 1 elif ev.code == "t": _year = _today.year; _month = _today.month main() ``` -------------------------------- ### Multi-Prompt Form Example Source: https://pyratatui.github.io/pyratatui/reference/prompts This example demonstrates a multi-field form using `TextPrompt` and `PasswordPrompt` within a `Terminal` context. It handles tab navigation, Esc to exit, and Enter to submit the last field. ```python import time from pyratatui import ( Terminal, Layout, Constraint, Direction, Block, Style, Color, TextPrompt, PasswordPrompt, TextState, ) fields = [ ("username", TextState(), TextPrompt("Username: ")), ("password", TextState(), PasswordPrompt("Password: ")), ] current = 0 fields[0][1].focus() with Terminal() as term: term.hide_cursor() running = True while running: _cur = current def ui(frame, _fields=fields, _c=_cur): area = frame.area rows = ( Layout() .direction(Direction.Vertical) .constraints([Constraint.length(3)] * len(_fields) + [Constraint.min(0)]) .split(area) ) for i, (name, state, prompt) in enumerate(_fields): block = Block().bordered().title(f" {name} ") \ .style(Style().fg(Color.cyan() if i == _c else Color.gray())) inner = block.inner(rows[i]) frame.render_widget(block, rows[i]) if isinstance(prompt, PasswordPrompt): frame.render_password_prompt(prompt, inner, state) else: frame.render_text_prompt(prompt, inner, state) term.draw(ui) ev = term.poll_event(timeout_ms=50) if ev: name, state, prompt = fields[current] if ev.code == "Tab": state.blur() current = (current + 1) % len(fields) fields[current][1].focus() elif ev.code == "Esc": running = False elif ev.code == "Enter" and current == len(fields) - 1: # Last field β€” submit running = False else: state.handle_key(ev) ``` -------------------------------- ### Implement Vim-style Modal Editing Source: https://pyratatui.github.io/pyratatui/reference/textarea Example logic for switching between NORMAL and INSERT modes. ```python if mode == "NORMAL": if ev.code == "i": mode = "INSERT" elif ev.code == "h": ta.move_cursor(CursorMove.Back) elif ev.code == "u": ta.undo() # ... elif mode == "INSERT": if ev.code == "Esc": mode = "NORMAL" else: ta.input_key(ev.code, ev.ctrl, ev.alt, ev.shift) ``` -------------------------------- ### Render PasswordPrompt Source: https://pyratatui.github.io/pyratatui/reference/prompts Example of rendering a password prompt within a draw callback. ```python def ui(frame): frame.render_password_prompt( PasswordPrompt("Password: "), area, state, ) ``` -------------------------------- ### Style Usage Examples Source: https://pyratatui.github.io/pyratatui/reference/style Common patterns for creating styled text, including theming via patch. ```python from pyratatui import Style, Color, Modifier # Bold cyan on dark background Style().fg(Color.cyan()).bg(Color.black()).bold() # Italic gray for secondary text Style().fg(Color.gray()).italic() # Highlighted selection row Style().fg(Color.black()).bg(Color.cyan()).bold() # Error state Style().fg(Color.red()).bold().underlined() # Combine via patch (theming) header_style = Style().fg(Color.white()).bold() selected = header_style.patch(Style().bg(Color.blue())) ``` -------------------------------- ### Complete Example: Scrollable and Draggable Popup Source: https://pyratatui.github.io/pyratatui/reference/popups A full example demonstrating a scrollable and draggable popup within a terminal application. It includes event handling for movement and closing the popup. ```python import time from pyratatui import ( Color, KnownSizeWrapper, Paragraph, Popup, PopupState, Style, Terminal, ) lines = [f" {i:03d}. Item number {i}" for i in range(1, 31)] wrapper = KnownSizeWrapper(lines, width=40, height=8) state = PopupState() bg = Paragraph.from_string("background").style(Style().fg(Color.dark_gray())) popup = ( Popup(wrapper) .title(" Scrollable & Draggable ") .style(Style().fg(Color.white()).bg(Color.dark_gray())) ) with Terminal() as term: while True: def ui(frame, _p=popup, _s=state): frame.render_widget(bg, frame.area) frame.render_stateful_popup(_p, frame.area, _s) term.draw(ui) ev = term.poll_event(timeout_ms=50) if ev is None: continue if ev.code in ("q", "Esc"): break elif ev.code == "Up": state.move_up(1) elif ev.code == "Down": state.move_down(1) elif ev.code == "Left": state.move_left(1) elif ev.code == "Right": state.move_right(1) elif ev.code == "r": state.reset() ``` -------------------------------- ### Develop install (editable) Pyratatui Source: https://pyratatui.github.io/pyratatui/installation Installs Pyratatui in editable mode for development. Changes to Rust source require re-running `maturin develop`. ```bash git clone https://github.com/pyratatui/pyratatui.git cd pyratatui pip install maturin maturin develop # debug build (fast compile, slower runtime) ``` -------------------------------- ### Build a distributable wheel for Pyratatui Source: https://pyratatui.github.io/pyratatui/installation Builds a wheel file for Pyratatui using Maturin. The wheel is then installed using pip. ```bash maturin build --release # Wheel appears in target/wheels/ pip install target/wheels/pyratatui-*.whl ``` -------------------------------- ### Configure Block Borders Source: https://pyratatui.github.io/pyratatui/reference/widgets Example of enabling specific borders using the borders method. ```python # Only top and bottom borders Block().borders(top=True, right=False, bottom=True, left=False) ``` -------------------------------- ### Handle key events Source: https://pyratatui.github.io/pyratatui/reference/terminal Example of polling for events and handling specific key codes. ```python ev = term.poll_event(timeout_ms=100) if ev: if ev.code == "q": running = False elif ev.code == "c" and ev.ctrl: running = False elif ev.code == "Up": state.select_previous() elif ev.code == "Down": state.select_next() elif ev.code == "Enter": confirm_selection() elif ev.code == "F5": refresh() ``` -------------------------------- ### Render TextPrompt Source: https://pyratatui.github.io/pyratatui/reference/prompts Example of rendering a text prompt within a draw callback. ```python def ui(frame): frame.render_text_prompt( TextPrompt("Search: "), area, state, ) ``` -------------------------------- ### Build a Release Wheel for Pyratatui Source: https://pyratatui.github.io/pyratatui/build/build_scripts Build a release-ready wheel file for Pyratatui. After building, install the wheel using pip. The output wheel file is located in the 'target/wheels/' directory. ```bash maturin build --release ``` ```bash # Install the built wheel pip install target/wheels/pyratatui-*.whl ``` -------------------------------- ### First Fade Effect Example Source: https://pyratatui.github.io/pyratatui/tutorial/tachyonfx_effects Demonstrates how to create and apply a foreground fade effect using `EffectManager`. This example requires importing `time`, `Terminal`, and various `pyratatui` components. The effect fades the foreground color to black over 1500 milliseconds using a SineOut interpolation. ```python import time from pyratatui import ( Terminal, Paragraph, Block, Style, Color, Effect, EffectManager, Interpolation, ) mgr = EffectManager() mgr.add(Effect.fade_from_fg(Color.black(), 1500, Interpolation.SineOut)) last = time.monotonic() with Terminal() as term: term.hide_cursor() while True: now = time.monotonic() elapsed_ms = int((now - last) * 1000) last = now _ms = elapsed_ms def ui(frame, _mgr=mgr, ms=_ms): area = frame.area # Step 1: render widgets frame.render_widget( Paragraph.from_string("Fading in…") .block(Block().bordered().title(" Fade Demo ")) .style(Style().fg(Color.white())), area, ) # Step 2: apply effects frame.apply_effect_manager(_mgr, ms, area) term.draw(ui) ev = term.poll_event(timeout_ms=16) # ~60 fps ceiling if ev and ev.code == "q": break term.show_cursor() ``` -------------------------------- ### Three-Panel Layout Example Source: https://pyratatui.github.io/pyratatui/examples/minimal_examples Demonstrates creating a vertical layout with three distinct panels using `Layout`, `Constraint`, and `Direction`. Each panel renders a `Paragraph` widget. ```Python # examples/02_layout.py from pyratatui import ( Terminal, Layout, Constraint, Direction, Paragraph, Block, Style, Color, ) with Terminal() as term: while True: def ui(frame): chunks = ( Layout() .direction(Direction.Vertical) .constraints([ Constraint.length(3), Constraint.fill(1), Constraint.length(1), ]) .split(frame.area) ) frame.render_widget( Paragraph.from_string("My App") .centered() .block(Block().bordered()), chunks[0], ) frame.render_widget( Paragraph.from_string("Main content.\n\nPress q to quit.") .block(Block().bordered().title("Content")) .wrap(True), chunks[1], ) frame.render_widget( Paragraph.from_string(" q: Quit"), chunks[2], ) term.draw(ui) ev = term.poll_event(timeout_ms=100) if ev and ev.code == "q": break ``` -------------------------------- ### Render Paragraph Examples Source: https://pyratatui.github.io/pyratatui/reference/widgets Various ways to render paragraphs including simple, wrapped, and rich styled text. ```python from pyratatui import Paragraph, Text, Line, Span, Style, Color, Block # Simple frame.render_widget( Paragraph.from_string("Hello, World!") .block(Block().bordered().title("Info")), area, ) # Wrapped long content frame.render_widget( Paragraph.from_string(long_text).wrap(True), area, ) # Rich styled text frame.render_widget( Paragraph(Text([ Line([Span("Status: "), Span("OK", Style().fg(Color.green()))]), Line.from_string("All systems nominal"), ])).block(Block().bordered()), area, ) ``` -------------------------------- ### Layout Constraints: Fill Example Source: https://pyratatui.github.io/pyratatui/faq Demonstrates how `Constraint.fill(1)` distributes remaining space after fixed constraints are satisfied. Ensure the sum of fixed constraints does not exceed the available area. ```rust chunks = (Layout() .constraints([Constraint.fill(1), Constraint.fill(1)]) .split(area)) ``` ```rust # area.height = 24 # 3 + 20 + 3 = 26 > 24 β†’ fill gets nothing Layout().constraints([ Constraint.length(3), Constraint.length(20), # too large Constraint.fill(1), Constraint.length(3), ]) ``` -------------------------------- ### QR Code Widget Example Source: https://pyratatui.github.io/pyratatui/examples/minimal_examples Displays a QR code for a given URL with inverted colors and a bordered block. The application quits on 'q' or 'Esc'. ```python from pyratatui import Block, QrCodeWidget, QrColors, Terminal qr = QrCodeWidget("https://ratatui.rs").colors(QrColors.Inverted) with Terminal() as term: while True: def ui(frame, _qr=qr): blk = Block().bordered().title(" Scan Me ") inner = blk.inner(frame.area) frame.render_widget(blk, frame.area) frame.render_qrcode(_qr, inner) term.draw(ui) ev = term.poll_event(timeout_ms=30_000) if ev and ev.code in ("q", "Esc"): break ``` -------------------------------- ### Quick Start: Render QR Code Source: https://pyratatui.github.io/pyratatui/reference/qrcode Basic usage of QrCodeWidget to render a QR code for a given URL within a bordered block. Requires setting up a ratatui Terminal and drawing loop. ```python from pyratatui import QrCodeWidget, QrColors, Block, Terminal qr = QrCodeWidget("https://ratatui.rs").colors(QrColors.Inverted) with Terminal() as term: while True: def ui(frame): block = Block().bordered().title(" QR Code ") inner = block.inner(frame.area) # compute inner area frame.render_widget(block, frame.area) frame.render_qrcode(qr, inner) term.draw(ui) ev = term.poll_event(timeout_ms=30_000) if ev and ev.code == "q": break ``` -------------------------------- ### Scrollbar Widget Example Source: https://pyratatui.github.io/pyratatui/reference/widgets Renders a scrollbar with custom thumb and track styles. Requires ScrollbarState for content length and position. ```python from pyratatui import Scrollbar, ScrollbarState, ScrollbarOrientation, Style, Color scroll_state = ScrollbarState().content_length(100).position(20) frame.render_stateful_scrollbar( Scrollbar() .thumb_style(Style().fg(Color.cyan())) .track_style(Style().fg(Color.dark_gray())), area, scroll_state, ) ``` -------------------------------- ### Initialize and Configure Tree Widget Source: https://pyratatui.github.io/pyratatui/reference/tree_widget Create a Tree widget with nested items and apply a bordered block with a title. This is the initial setup for displaying a tree structure. ```python from pyratatui import Tree, TreeItem, TreeState, Block items = [ TreeItem("Documents", [ TreeItem("report.pdf"), TreeItem("notes.md"), ]), TreeItem("Downloads"), ] tree = Tree(items).block(Block().bordered().title(" Files ")) state = TreeState() # In render loop: # frame.render_stateful_tree(tree, area, state) ``` -------------------------------- ### Initialize Layout Source: https://pyratatui.github.io/pyratatui/reference/layout Create a new Layout instance with default settings. ```python Layout() ``` -------------------------------- ### Run Hello World Source: https://pyratatui.github.io/pyratatui/tutorial/quickstart Command to execute the hello.py script. ```bash python hello.py ``` -------------------------------- ### Basic Async pyratatui App Source: https://pyratatui.github.io/pyratatui/tutorial/async_updates A simple example of an asynchronous pyratatui application. It uses AsyncTerminal to render a paragraph and handles events in a loop. The `events()` method keeps running by default; use `stop_on_quit=True` to exit on 'q'. ```python import asyncio from pyratatui import AsyncTerminal, Paragraph, Block, Style, Color async def main(): async with AsyncTerminal() as term: async for ev in term.events(fps=30): def ui(frame): frame.render_widget( Paragraph.from_string("Async pyratatui! Press q to quit.") .block(Block().bordered().title("Hello Async")) .style(Style().fg(Color.green())), frame.area, ) term.draw(ui) # events() now keeps running by default; pass stop_on_quit=True to exit on 'q' asyncio.run(main()) ``` -------------------------------- ### Wheel Naming Convention Example Source: https://pyratatui.github.io/pyratatui/build/packaging Example of a generated wheel filename produced by Maturin. ```text pyratatui-0.2.7-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl ``` -------------------------------- ### Building a Menu Source: https://pyratatui.github.io/pyratatui/reference/menu_widget Define menu items and initialize the navigation state. ```python from pyratatui import MenuItem, MenuState items = [ MenuItem.item("File", "file"), MenuItem.group("Edit", [ MenuItem.item("Copy", "copy"), MenuItem.item("Paste", "paste"), ]), ] state = MenuState(items) state.activate() ``` -------------------------------- ### Implement the main application loop Source: https://pyratatui.github.io/pyratatui/tutorial/async_updates Sets up the asynchronous main loop to manage terminal state and rendering. ```python async def main(): metrics_task = asyncio.create_task(simulate_metrics()) async with AsyncTerminal() as term: term.hide_cursor() async for ev in term.events(fps=20): # Snapshot state for this frame cpu = state["cpu"] mem = state["mem"] reqs = state["requests"] hist = list(state["history"]) log = list(state["log"]) tick = state["tick"] # Capture snapshots into closure default args to avoid late-binding def ui(frame, _cpu=cpu, _mem=mem, _reqs=reqs, _hist=hist, _log=log, _tick=tick): build_ui(frame, _cpu, _mem, _reqs, _hist, _log, _tick) term.draw(ui) term.show_cursor() metrics_task.cancel() try: await metrics_task except asyncio.CancelledError: pass asyncio.run(main()) ``` -------------------------------- ### Install Maturin for building Python packages Source: https://pyratatui.github.io/pyratatui/installation Installs Maturin, a build tool for Rust-based Python packages. Required when building Pyratatui from source. ```bash pip install maturin ``` -------------------------------- ### Configure Animated Startup Sequence Source: https://pyratatui.github.io/pyratatui/examples/advanced_examples Initializes the EffectManager for handling startup animations. ```python """ Animated startup with TachyonFX sequence effect. """ import time from pyratatui import ( Terminal, Paragraph, Block, Style, Color, Effect, EffectManager, Motion, Interpolation, ) mgr = EffectManager() last = time.monotonic() ``` -------------------------------- ### Cross-Compile Linux aarch64 Wheel Source: https://pyratatui.github.io/pyratatui/build/build_scripts Build a Linux aarch64 wheel from a macOS host. This requires installing the target architecture for Rust, installing Maturin with Zig support, and specifying the target and Zig linker during the build. ```bash pip install maturin[zig] rustup target add aarch64-unknown-linux-gnu maturin build --release --strip \ --target aarch64-unknown-linux-gnu \ --zig ``` -------------------------------- ### Verify Pyratatui Build Source: https://pyratatui.github.io/pyratatui/build/build_scripts Import the pyratatui library and print its version information. It also includes a sanity check by creating a Buffer and Rect, simulating a no-display render to confirm basic functionality. ```python import pyratatui print(pyratatui.__version__) # e.g. "0.2.7" print(pyratatui.__ratatui_version__) # "0.29" # Sanity check: run a no-display render from pyratatui import Buffer, Rect, Paragraph, Text buf = Buffer(Rect(0, 0, 40, 5)) # (widgets write into buf in tests via ratatui's stateless render) print("Build OK") ``` -------------------------------- ### Get Terminal Area Source: https://pyratatui.github.io/pyratatui/reference/terminal Retrieve the current terminal dimensions as a Rect object. ```python rect = term.area() ``` -------------------------------- ### Build Pyratatui from source Source: https://pyratatui.github.io/pyratatui/faq Commands for building from source or caching wheels to avoid repeated Rust compilation. ```bash pip wheel pyratatui -w ./cache/ ``` ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` -------------------------------- ### Initialize ListItem Source: https://pyratatui.github.io/pyratatui/reference/widgets Methods for creating and styling list items. ```python ListItem(text: str, style: Style | None = None) ListItem.from_text(text: Text) # from a Text object item.style(style: Style) # return new item with style ``` -------------------------------- ### Implement Terminal Startup Loop Source: https://pyratatui.github.io/pyratatui/examples/advanced_examples Manages the terminal lifecycle, rendering the splash screen and applying effects until the startup sequence completes. ```python with Terminal() as term: term.hide_cursor() while True: now = time.monotonic() ms = int((now - last) * 1000) last = now def ui(frame, _mgr=mgr, _ms=ms): area = frame.area frame.render_widget( Paragraph.from_string(SPLASH) .block(Block().bordered().border_style(Style().fg(Color.cyan()))) .style(Style().fg(Color.cyan()).bold()) .centered(), area, ) if _mgr.has_active(): frame.apply_effect_manager(_mgr, _ms, area) term.draw(ui) ev = term.poll_event(timeout_ms=16) if ev and ev.code == "q": break # Transition to main app after startup completes if not mgr.has_active(): term.poll_event(timeout_ms=800) # brief hold break # enter main loop here term.show_cursor() print("Startup complete β€” entering main app.") ``` -------------------------------- ### Style Constructor Source: https://pyratatui.github.io/pyratatui/reference/style Initialize an empty style. ```python Style() # Empty style (inherits everything from parent) ``` -------------------------------- ### Run application helper Source: https://pyratatui.github.io/pyratatui/reference/terminal Synchronous wrapper to create a terminal and run a draw loop. ```python from pyratatui import run_app def my_ui(frame): frame.render_widget(Paragraph.from_string("Hello!"), frame.area) run_app(my_ui, fps=30) ``` -------------------------------- ### Create TextArea Instance Source: https://pyratatui.github.io/pyratatui/reference/textarea Initialize an empty or pre-filled TextArea widget. ```python from pyratatui import TextArea ta = TextArea() # empty ta = TextArea.from_lines(["Line 1", "Line 2"]) # pre-filled ```