[go: up one dir, main page]

Skip to content

2024

Anatomy of a Textual User Interface

My bad 🤦

The date is wrong on this post—it was actually published on the 2nd of September 2024. I don't want to fix it, as that would break the URL.

I recently wrote a TUI to chat to an AI agent in the terminal. I'm not the first to do this (shout out to Elia and Paita), but I may be the first to have it reply as if it were the AI from the Aliens movies?

Here's a video of it in action:

Now let's dissect the code like Bishop dissects a facehugger.

Behind the Curtain of Inline Terminal Applications

Textual recently added the ability to run inline terminal apps. You can see this in action if you run the calculator example:

Inline Calculator

The application appears directly under the prompt, rather than occupying the full height of the screen—which is more typical of TUI applications. You can interact with this calculator using keys or the mouse. When you press Ctrl+C the calculator disappears and returns you to the prompt.

Here's another app that creates an inline code editor:

from textual.app import App, ComposeResult
from textual.widgets import TextArea


class InlineApp(App):
    CSS = """
    TextArea {
        height: auto;
        max-height: 50vh;
    }
    """

    def compose(self) -> ComposeResult:
        yield TextArea(language="python")


if __name__ == "__main__":
    InlineApp().run(inline=True)

This post will cover some of what goes on under the hood to make such inline apps work.

It's not going to go in to too much detail. I'm assuming most readers will be more interested in a birds-eye view rather than all the gory details.

Remote memory profiling with Memray

Memray is a memory profiler for Python, built by some very smart devs at Bloomberg. It is a fantastic tool to identify memory leaks in your code or other libraries (down to the C level)!

They recently added a Textual interface which looks amazing, and lets you monitor your process right from the terminal:

Memray