Skip to content

Tutorial Workbench

rafageist edited this page Dec 4, 2026 · 2 revisions

Tutorial step 6: a workbench

Steps 1 to 5 built a desktop from its parts. Step 6 is a whole application made of TurboFrame's larger components: a small code editor with the project's explorer, editors, Find and Replace, Find in files, Go to file and a command palette, a Run command with its output, Options > Colors and Options > Language, and settings that are kept from one start to the next. Its own texts are in English and Spanish. (Step 5 comes first.)

pip install "turboframe[watch] @ git+https://github.com/divengine/turboframe@v0.3.0"
pip install "textual[syntax]"            # optional: syntax colours in the editors
python examples/workbench/workbench.py [FOLDER] [--language es]

The workbench: the explorer opens a file, an edit is saved, Ctrl+P goes to a file, F5 finds in files, F9 runs

The program is examples/workbench/workbench.py, about 290 lines with its comments. This page walks through it. tests/test_examples_apps.py drives it, and acceptance/terminal/test_rt_examples.py runs it in a real terminal.

Key Does
Enter on a file in the explorer opens it beside the tree
F2, F3, Alt+F3 Save, Open, Close
Ctrl+F, Ctrl+L, Ctrl+G Find, Search again, Go to line (Replace is in the Search menu)
F5 Find in files
Ctrl+P, Alt+P Go to file, the command palette
F9 Run the Python file in the active editor
F4, F6 the explorer, the next window
Alt+F10 in the explorer its local menu: new file, rename, delete, cut, copy, paste, move
Alt+X exit, asking about unsaved changes

The application's bases

class Workbench(LanguageMixin, PaletteMixin, FindInFilesMixin, SearchMixin, EditorMixin, ExplorerMixin,
                DesktopApp):
    """The mixins first, DesktopApp last: each mixin's hooks call super(), so all of them hear an open or a
    save whatever their order."""

    TITLE = "Workbench"
    MASK_HINT = "*.py;*.md"  # Find in files: the example under its file masks

Each mixin brings one feature's flows and asks the application for the rest through hooks that have defaults (Application Mixins has the whole picture):

Mixin Brings Guide
ExplorerMixin the folder's tree and its file operations The Explorer
EditorMixin New, Open, Save, Save as, Save all, Close, Go to line The Editor
SearchMixin Find, Replace, Search again Search
FindInFilesMixin Find in files and its results window Search
PaletteMixin Go to file and the command palette Command Palette
LanguageMixin Options > Language Languages

DesktopApp already has ColorsMixin (Options > Colors) and draws the scroll bars' thumbs in whole cells, as Turbo Vision did.

One store for every setting

    def __init__(self, folder: Path, store=None) -> None:
        # One store for every setting: the colours, the histories, the language, the recent files.
        self.store = store if store is not None else JsonStore(APP)
        self.colors_store = self.store  # Options > Colors (DesktopApp starts in what it keeps)
        self.language_store = self.store  # Options > Language
        self.language_domain = DOMAIN
        history.set_store(self.store)  # the input lines' histories (Find, Open...)
        self.recent = Recent(self.store)
        self.reopen = self.recent.entries("files")[:RECENT_SHOWN]  # File > 1..5, read before the menus are made
        super().__init__()
        self.folder = Path(folder).resolve()  # the explorer's, Find in files' and Go to file's folder
        self.recent.add("folders", self.folder)

JsonStore("turboframe-workbench") is ~/.config/turboframe-workbench/config.json (%APPDATA% on Windows). Every component that keeps something takes a store, any object with load() -> dict and save(dict), and each writes its own keys. So one file holds the palette, the colour depth, the Find and Open histories, the language and the recent folders and files. The tests pass a MemoryStore instead. See Settings and Recent Files.

folder is the attribute the mixins read by default: the explorer shows it, Find in files and Go to file search it. With no folder on the command line, main() opens the last one (Recent(store).entries("folders")).

Menus, keys and one place for the commands

The menus are the application's own. The commands of TurboFrame's components are constants: Command.SAVE, CM_FIND, CM_GOTO_FILE, CM_LANGUAGE and the others. The application numbers its own commands from Command.USER; TurboFrame's sit in FRAMEWORK_COMMANDS (Command.USER + 10000 and up), so the two never meet.

CM_FIND_IN_FILES = Command.USER + 1
CM_EXPLORER = Command.USER + 2
CM_RUN = Command.USER + 3
...

def key(binding: str, command: int) -> Binding:
    """A key that runs a command wherever the focus is (priority: before the focused widget's own keys)."""
    return Binding(binding, f"cmd({int(command)})", show=False, priority=True)

A menu item, a status line item and a key all post the same CommandMessage. The application takes its own and leaves the others (F10, a window's close box) to textual-vision:

    def on_command_message(self, message: CommandMessage) -> None:
        if message.command in MINE:  # the others (F10, a window's own) are textual-vision's
            message.stop()
            message.prevent_default()
            self.run_command(message.command, message.info)

    @work(group="command")
    async def run_command(self, command: int, info: object = None) -> None:
        """Every command runs here, in a worker: a dialog is awaited (``run_dialog``) as a modal box."""
        if command == Command.QUIT:
            if await self.close_all():  # asks about unsaved changes
                self.exit()
        elif command == CM_FIND_IN_FILES:
            await self.find_in_files()
        ...
        else:  # each mixin's dispatcher says whether the command was its own
            await self.editor_command(command, info) or await self.search_command(command) \
                or await self.palette_command(command) or await self.language_command(command)

Each mixin's dispatcher returns True when the command was its own, so they chain with or.

The workbench: the explorer, two editors and Find in files' results

The hooks it overrides

The defaults put a new window wherever textual-vision does. The workbench keeps the explorer on the left, the editors at the top of the rest, and the tool windows (results, a run's log, the Output) along the bottom:

    def place_editor(self, window: EditorWindow) -> None:
        """EditorMixin: a new editor goes beside the explorer, the editors tiled there."""
        super().place_editor(window)
        self.call_after_refresh(self.arrange)

    def show_find_results(self, window):
        """FindInFilesMixin: the results beside the explorer too."""
        window = super().show_find_results(window)
        self.call_after_refresh(self.arrange)
        return window

Two more hooks connect the recent files: every file opened is remembered, and Go to file lists the open files and then those opened in earlier sessions first.

    def after_open(self, window: EditorWindow) -> None:
        super().after_open(window)  # cooperative: the other mixins hear it too
        if window.path is not None:
            self.recent.add("files", window.path)

    def palette_recent_files(self) -> list[str]:
        """PaletteMixin: Go to file lists the files open, then those opened lately, first."""
        shown = super().palette_recent_files()
        for path in self.recent.entries("files"):
            if path.is_relative_to(self.folder):
                rel = path.relative_to(self.folder).as_posix()
                if rel not in shown:
                    shown.append(rel)
        return shown
Ctrl+P: Go to file, filtered as you type Alt+P: the commands of the menu bar, filtered
Ctrl+P: Go to file, filtered as you type Alt+P: every command of the menus
F5: Find in files Alt+F10 in the explorer: its local menu
F5: Find in files, with masks and options Alt+F10 in the explorer: its local menu

Running a file, and the Output window

Run > Run file saves the active editor if it has changes, runs it with Python and shows what it prints, line by line, in a LogWindow. Run > Check syntax compiles the text and says the verdict in the OutputWindow, moving the cursor to the error when there is one. See Log and Output Windows.

        log = LogWindow(_("Run: {name}").format(name=window.path.name), number=self.free_number())
        self.insert_window(log)
        self.arrange()
        with self.busy(_("Running")):
            try:
                result = await process.run([sys.executable, str(window.path)], cwd=window.path.parent,
                                           on_line=log.add, timeout=60)
                log.add(_("[exit code {code}]").format(code=result.code))
            except TimeoutError:
                log.add(_("[stopped after 60 seconds]"))

Run: the program's output in a log window; Check syntax: the Output window

Its own texts, in two languages

The workbench marks its texts with its own catalogue, a Domain. DOMAIN.use(language) switches its texts and TurboFrame's together:

DOMAIN = i18n.Domain("workbench", HERE / "locale")
_ = DOMAIN.gettext

def main(argv: list[str] | None = None) -> None:
    ...
    store = JsonStore(APP)
    # The language first: the menus' texts are made when the application starts.
    DOMAIN.use(i18n.choose_language(env="WORKBENCH_LANGUAGE", setting=store.get("language"))
               if args.language in (None, "auto") else args.language)

Options > Language keeps the choice in the store, for the next start. The catalogue in examples/workbench/locale was made with python -m turboframe.i18n_tools, and a test checks it; Translating Your Application shows how.

The workbench in Spanish, its Search menu open Options > Language
--language es: the workbench's menus and TurboFrame's texts Options > Language, applied from the next start

More examples

Each of these is a separate, smaller application that shows one component with what it needs:

Clone this wiki locally