Skip to content

Tutorial Tasks

rafageist edited this page Dec 2, 2026 · 2 revisions

Tutorial step 5: tasks

Step 5 adds work that takes a while. It runs a job under the progress box, runs a command with its output streamed into a window, reads the repository's changes from git into a diff viewer, and shows a spinner in the status line while the application is busy. (Step 4 comes first.)

python examples/tutorial/step5_tasks.py
Run > Count lines, under the progress box Git changes, side by side

A job under the progress box, then a command's output

The program, step5_tasks.py:

# SPDX-License-Identifier: GPL-3.0-or-later
"""Step 5: tasks. A job under the progress box (Esc stops it), a command's output streamed into a window,
the repository's changes from git and a diff viewer, and a spinner while the application is busy. Every
process the application starts ends with it.

    python examples/tutorial/step5_tasks.py
"""

from __future__ import annotations

import asyncio
import sys
from pathlib import Path

from textual import work
from textual.app import ComposeResult
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
from step3_dialogs import CM_ABOUT, CM_FIND, CM_OPEN, CM_RENAME
from step4_themes import CM_COLORS, CM_ROLES, Themes
from turboframe import git, process
from turboframe.ui.diffview import DiffView
from turboframe.ui.icons import mark_for
from turboframe.ui.progress import ProgressDialog, run_with_progress
from turboframe.ui.windows import LocationsWindow, MessageItem, TVWindow

CM_COUNT = Command.USER + 30
CM_RUN = Command.USER + 31
CM_CHANGES = Command.USER + 32
ROOT = Path(__file__).resolve().parents[2]  # the repository this example lives in


class DiffWindow(TVWindow):
    def __init__(self, title: str, number: int) -> None:
        super().__init__(title, number=number)
        self.view = DiffView()

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


class Tasks(Themes):
    TITLE = "Tasks"

    def __init__(self, store=None, root: Path = ROOT) -> None:
        super().__init__(store)
        self.root = root
        self.counted: int | None = None
        DiffView.store = self.store  # unified or side by side (S), remembered

    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("~R~un", MenuItem("~C~ount lines", CM_COUNT, "F9"), MenuItem("~P~ython's version", CM_RUN),
                    MenuItem("~G~it changes", CM_CHANGES)),
            SubMenu("~O~ptions", MenuItem("~C~olors...", CM_COLORS)),
            SubMenu("~W~indow", MenuItem("~R~oles", CM_ROLES), 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("~F9~ Count lines", "f9", CM_COUNT), StatusItem("~F3~ Open", "f3", CM_OPEN),
                                      StatusItem("~F6~ Next", "f6", CM_NEXT), StatusItem("~Alt+X~ Exit", "alt+x", Command.QUIT)])]

    def start(self) -> None:
        self.hint("Run > Count lines, Python's version, Git changes")  # an empty desktop: Run makes windows

    def handle(self, command: int) -> bool:
        handlers = {CM_COUNT: self.count_lines, CM_RUN: self.run_python, CM_CHANGES: self.changes}
        if command not in handlers:
            return super().handle(command)
        handlers[command]()
        return True

    @work
    async def count_lines(self) -> None:
        """A job under the progress box: rows that change, a bar that fills, Esc to stop it."""
        files = sorted((self.root / "src").rglob("*.py"))
        dialog = ProgressDialog("Count lines", [("File", "")])

        async def job() -> int:
            total = 0
            for n, path in enumerate(files):
                dialog.set("File", f"{mark_for(path)[0]} {path.name}")
                total += len(path.read_text(encoding="utf-8").splitlines())
                dialog.progress((n + 1) / len(files))
                await asyncio.sleep(0.03)
            return total

        self.counted = await run_with_progress(self, dialog, job(),
                                               lambda total: ("Success", True, [("Lines", f"{total:,}")]))

    @work
    async def run_python(self) -> None:
        """A command's output, line by line, into a window; the process is tracked and ends with the app."""
        window = LocationsWindow("Output", number=self.free_number())
        self.insert_window(window)
        lines: list[MessageItem] = []

        def line(text: str) -> None:
            lines.append(MessageItem(text))
            window.show(list(lines))

        with self.busy("Running Python"):
            result = await process.run([sys.executable, "-c", "import sys, platform; print(sys.version); "
                                        "print(platform.platform())"], on_line=line, timeout=30)
        line(f"[exit code {result.code}]")

    @work
    async def changes(self) -> None:
        """What changed in the repository (git status), and the diff of the first change."""
        with self.busy("Reading git"):
            status = await git.status(self.root)
            changed = [c for c in status.changes if c.area != "untracked"]
            text = await git.diff_of(self.root, changed[0]) if changed else ""
        window = DiffWindow(f"Changes on {status.branch or 'HEAD'}", self.free_number())
        self.insert_window(window)
        self.call_after_refresh(window.zoom)  # the whole desktop: a diff wants the width
        if text:
            self.call_after_refresh(window.view.show, text)
        else:
            self.call_after_refresh(window.view.show_message, "No changes in tracked files.")


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

The progress box

run_with_progress(app, dialog, job, verdict) shows a ProgressDialog while the coroutine job runs, and returns its result, or None when the user pressed Esc, which cancels the job. Meanwhile:

  • dialog.set(label, value) changes a row; the box grows when a row is new;
  • dialog.progress(fraction) fills the bar, with the percentage; with None, a block goes back and forth;
  • the Time row counts by itself.

When the job ends, verdict(result) gives a word ("Success"), whether it went well, and the final rows. The box stays up with the verdict until a key is pressed, or for a moment: 2 seconds after a success, 5 after a problem. See Progress.

Running a command

process.run(argv, on_line=..., timeout=...) runs a command to its end, calls on_line for each line of its output (both streams), and returns a Result(code, output). Cancel the worker and the process is killed. Every process TurboFrame starts is tracked and ends with the application, even when the application is killed (on Linux). See Processes.

Git and the diff viewer

turboframe.git runs the system's git and reads its machine formats: status(root) gives the branch and the changes, diff_of(root, change) a file's diff, and there are the log, blame, branches, remotes, stage, commit, merge and stashes. DiffView draws a diff, unified or side by side (S switches); N and P move between hunks, and Enter posts LineChosen to open the file there. See Git and Diffs.

Busy

with self.busy("Running Python"): shows a spinner and the label in the status line until the block ends.

That is the desktop's part of the tutorial. Step 6 puts TurboFrame's larger components together in a whole application: an editor with an explorer, search, a command palette and kept settings. The guides, in the sidebar, go further into each component, and the API Reference lists every public name.

Clone this wiki locally