Skip to content

Tutorial Dialogs

rafageist edited this page Dec 2, 2026 · 2 revisions

Tutorial step 3: dialogs

Step 3 adds File > Open, Edit > Find with a history of what you searched, an input dialog, a message box, and a settings store that keeps the histories between runs. (Step 2 comes first.)

python examples/tutorial/step3_dialogs.py
Edit > Find Down in the Find line opens its history
File > Open Help > About, a message box

Find with its history, then File Open

The program, step3_dialogs.py:

# SPDX-License-Identifier: GPL-3.0-or-later
"""Step 3: dialogs. File > Open, Edit > Find with its history, a message box, an input dialog, and a store
that keeps the histories between runs.

    python examples/tutorial/step3_dialogs.py
"""

from __future__ import annotations

import json
from pathlib import Path

from textual import work
from textual.app import ComposeResult
from textual.widgets import TextArea
from textual_vision.constants import Command
from textual_vision.menus import Menu, MenuItem, Separator, SubMenu
from textual_vision.status_line import StatusDef, StatusItem

from step2_windows import CM_CASCADE, CM_NEXT, CM_TILE, Windows
from turboframe.search import SearchError, SearchOptions, compile_pattern, find_wrapping
from turboframe.ui import history
from turboframe.ui.dialogs import FileDialog, InputDialog, MessageBox, SearchDialog, information
from turboframe.ui.windows import TVWindow

CM_OPEN = Command.USER + 10
CM_FIND = Command.USER + 11
CM_RENAME = Command.USER + 12
CM_ABOUT = Command.USER + 13


class JsonStore:
    """Where an application keeps its settings: anything with load() -> dict and save(dict)."""

    def __init__(self, path: Path) -> None:
        self.path = path

    def load(self) -> dict:
        try:
            return json.loads(self.path.read_text(encoding="utf-8"))
        except (OSError, ValueError):
            return {}

    def save(self, data: dict) -> None:
        self.path.write_text(json.dumps(data, indent=1), encoding="utf-8")


class FileWindow(TVWindow):
    def __init__(self, path: Path, number: int) -> None:
        super().__init__(path.name, number=number)
        self.path = path
        self.editor = TextArea(path.read_text(encoding="utf-8", errors="replace"), read_only=True,
                               show_line_numbers=True, soft_wrap=False)

    def compose_content(self) -> ComposeResult:
        yield self.editor


class Dialogs(Windows):
    TITLE = "Dialogs"
    STORE = Path.home() / ".turboframe-tutorial.json"

    def __init__(self, store=None) -> None:
        self.store = store or JsonStore(self.STORE)
        super().__init__()
        history.set_store(self.store)  # every input line remembers what was accepted in it, in the store
        self.search = SearchOptions()
        self.find_text = ""

    def init_menu_bar(self) -> Menu:
        return Menu([
            SubMenu("~F~ile", MenuItem("~O~pen...", CM_OPEN, "F3"), MenuItem("~R~ename window...", CM_RENAME),
                    Separator(), MenuItem("E~x~it", Command.QUIT, "Alt+X")),
            SubMenu("~E~dit", MenuItem("~F~ind...", CM_FIND, "Ctrl+F")),
            SubMenu("~W~indow", MenuItem("~T~ile", CM_TILE), MenuItem("C~a~scade", CM_CASCADE),
                    MenuItem("~N~ext", CM_NEXT, "F6")),
            SubMenu("~H~elp", MenuItem("~A~bout...", CM_ABOUT)),
        ])

    def init_status_line(self) -> list[StatusDef]:
        return [StatusDef(0, 0xFFFF, [StatusItem("~F3~ Open", "f3", CM_OPEN), StatusItem("~Ctrl+F~ Find", "ctrl+f", CM_FIND),
                                      StatusItem("~F6~ Next", "f6", CM_NEXT), StatusItem("~Alt+X~ Exit", "alt+x", Command.QUIT)])]

    def start(self) -> None:
        self.open_file(Path(__file__))

    def handle(self, command: int) -> bool:
        handlers = {CM_OPEN: self.choose_file, CM_FIND: self.find, CM_RENAME: self.rename, CM_ABOUT: self.about}
        if command not in handlers:
            return super().handle(command)
        handlers[command]()
        return True

    def open_file(self, path: Path) -> FileWindow:
        window = FileWindow(path, self.free_number())
        self.insert_window(window)
        return window

    # Dialogs run modally from a worker: run_dialog returns the command they ended with.
    @work
    async def choose_file(self) -> None:
        dialog = FileDialog("Open a file", Path(__file__).parent, pattern="*.py")
        if await self.run_dialog(dialog) == Command.OK and dialog.chosen is not None:
            self.open_file(dialog.chosen)

    @work
    async def find(self) -> None:
        window = self.active_window()
        if not isinstance(window, FileWindow):
            return
        dialog = SearchDialog(replace=False, query=self.find_text, replacement="", options=self.search)
        if await self.run_dialog(dialog) != Command.OK:
            return
        self.find_text, self.search = dialog.search_text, dialog.options
        try:
            pattern = compile_pattern(self.find_text, self.search)
        except SearchError as error:
            await self.run_dialog(information("Find", str(error)))
            return
        editor = window.editor
        after = editor.document.get_index_from_location(editor.selection.end)  # from the cursor on
        found, wrapped = find_wrapping(editor.text, pattern, after)
        if found is None:
            await self.run_dialog(information("Find", f"{self.find_text!r} was not found."))
            return
        start = editor.document.get_location_from_index(found.start())
        end = editor.document.get_location_from_index(found.end())
        editor.selection = (start, end)
        editor.focus()
        self.hint(f"found at line {start[0] + 1}" + (" (from the top)" if wrapped else ""))

    @work
    async def rename(self) -> None:
        window = self.active_window()
        if window is None:
            return
        dialog = InputDialog("Rename window", "~N~ew title", window.title or "")
        if await self.run_dialog(dialog) == Command.OK and dialog.value:
            window.title = dialog.value

    @work
    async def about(self) -> None:
        box = MessageBox("About", "Dialogs: step 3 of the TurboFrame tutorial.",
                         [("O~K~", Command.OK, "ok")], width=48)
        await self.run_dialog(box)


if __name__ == "__main__":
    Dialogs().run()

Running a dialog

A dialog is modal: the application waits for it. In TurboFrame you wait from a worker, a Textual task (@work), so the screen keeps drawing meanwhile:

@work
async def choose_file(self) -> None:
    dialog = FileDialog("Open a file", Path.cwd(), pattern="*.py")
    if await self.run_dialog(dialog) == Command.OK and dialog.chosen is not None:
        self.open_file(dialog.chosen)

run_dialog returns the command the dialog ended with: Command.OK, Command.CANCEL (also Esc), Command.YES, Command.NO, or a command of a button of your own. What the dialog collected is on the dialog afterwards: FileDialog.chosen, SearchDialog.search_text and .options, InputDialog.value, GotoLineDialog.line.

Histories and the store

Every input line of TurboFrame's dialogs is a HistoryInput. Down, or a click on its ▐↓▌, opens what was accepted in it before, newest first. You can filter that list by typing. A dialog that ends with anything but Cancel adds what its lines hold to their histories.

Histories live in a store: any object with load() -> dict and save(dict). history.set_store(store) gives it to them; without one, they last for the session. JsonStore here is ten lines over a JSON file, so that the step shows what a store is. TurboFrame has a complete one, turboframe.config.JsonStore("myapp"): atomic saves in the user's config folder on Linux and Windows, and a set_value that stays quiet on a read-only home. The workbench uses it. Your application probably has a settings module already, and that module itself can be the store. See Settings and Recent Files.

Searching

SearchDialog collects the text and the options: case, whole words, regular expression, direction, origin. turboframe.search does the searching on plain text. compile_pattern(text, options) makes the pattern and raises SearchError with a message to show. find_wrapping(text, pattern, position) finds the next match, from the other end when there is none, and says whether it wrapped. See Search.

Next: Step 4: themes.

Clone this wiki locally