Skip to content

The Explorer

rafageist edited this page Dec 2, 2026 · 3 revisions

The Explorer

turboframe.ui.explorer is a project tree in a Turbo Vision window: folders and files, git's marks, the files' own members (classes, functions) unfolded under them, a filter you type into, and the file operations of a desktop.

Use it for the open folder of an editor or a project tool, with its file operations
Import from turboframe.ui.explorer import ExplorerMixin, ExplorerTree, ExplorerWindow
Needs nothing more; the watch extra (watchdog) to follow changes made by other programs
Extend subclass ExplorerTree (members, marks, hidden names, the watcher) and name it in ExplorerWindow.TREE; the mixin's hooks
from pathlib import Path

from turboframe.ui.app import DesktopApp
from turboframe.ui.explorer import ExplorerMixin


class Workbench(ExplorerMixin, DesktopApp):
    def __init__(self, folder: Path) -> None:
        super().__init__()
        self.folder = folder                        # the open folder; None: no explorer

    def on_mount(self) -> None:
        self.call_after_refresh(self.show_explorer)

show_explorer(*, focus=True) opens the explorer of folder (or brings it up) and returns its window; explorer_window() finds it. TurboFrame has no command for it: bind a key of yours (Window > Explorer, say). Without EditorMixin, the mixin opens files in plain EditorWindows; with it, files open through EditorMixin (see Application Mixins).

What the user does

Key
Enter, double click open a file; a folder opens and closes; a member opens its file there
Right, Left, Space unfold, fold, toggle (a folder, or a file's members)
Ins, F7 a new file, a new folder (subfolders are created too)
F2, Del rename, delete (never the open folder; unsaved editors are named first)
Ctrl+X, Ctrl+C, Ctrl+V, Esc cut, copy, paste in the folder under the bar, forget what was cut
Alt+F10, right click the local menu, with Move to...
Ctrl+R read the folder again
typing filter, also in folders never opened

Dragging a file or a folder onto a folder moves it, after asking. Nothing is created, moved or deleted outside the open folder. Editors follow a renamed or moved file, and a file with unsaved changes is never replaced or closed by an operation.

What changes outside

With the watch extra (see Files), the tree follows what other programs do in the folders it shows open: an entry created, deleted, renamed or moved appears at once, and the bar, the scroll and the filter stay where they were. Only a folder whose entries changed is read again. Without watchdog, or with watcher_factory = None, Ctrl+R reads a folder again.

Your application's parts: the tree

The tree's hooks live in a subclass of ExplorerTree, which your window names in TREE:

Hook Default
unfolds(path) False: no file unfolds
members(path, text) []: return your outline's members for the file's text (its editor's, unsaved changes included, else the disk's)
member_label(member) the member's label (or text), as Rich Text
folder_mark(path) None: what follows a folder's name (a package's mark, a module's version)
forget_folder_marks() nothing: the tree is read again, so marks you cached may be stale
HIDDEN_NAMES, HIDDEN_SUFFIXES version control, caches, virtual environments, compiled Python (files.HIDDEN_NAMES, plus .swp and .egg-info)
GIT_COLOURS git's status letters in the palette's colours
watcher_factory turboframe.watch.FolderWatcher when watchdog is installed, else None. Any callable taking (on_change, on_error) and returning an object with set_folders, is_current and stop
hint() the status line's text while the tree has the focus

A member is any object with children (its own members). Give it a key, so it is told apart when the file is read again, and start and end offsets, so the default go_to_member selects it. A file larger than MEMBERS_MAX_BYTES (2 MB) unfolds into nothing.

import ast
from dataclasses import dataclass, field

from turboframe.ui.app import DesktopApp
from turboframe.ui.explorer import ExplorerMixin, ExplorerTree, ExplorerWindow


@dataclass
class Member:
    label: str
    key: tuple
    start: int
    end: int
    children: list = field(default_factory=list)


class OutlineTree(ExplorerTree):
    HIDDEN_NAMES = ExplorerTree.HIDDEN_NAMES | {"build", "dist"}

    def unfolds(self, path) -> bool:
        return path.suffix == ".py"

    def members(self, path, text: str) -> list:
        try:
            module = ast.parse(text)
        except SyntaxError:
            return []
        lines = text.splitlines(keepends=True)
        found = []
        for node in module.body:
            if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
                start = sum(len(line) for line in lines[:node.lineno - 1])
                found.append(Member(node.name, (type(node).__name__, node.name), start, start + len(lines[node.lineno - 1])))
        return found


class OutlineWindow(ExplorerWindow):
    TREE = OutlineTree


class Workbench(ExplorerMixin, DesktopApp):
    EXPLORER = OutlineWindow

ExplorerWindow(root, *, icons=PLAIN, number=0) is the window: it moves, grows and zooms, and Window > Tile leaves it out, arranging the editors beside it. WIDTH (32) is its width.

Your application's parts: the mixin

The mixin's hooks, on your application:

Hook Default
folder the open folder (a class attribute, None)
EXPLORER ExplorerWindow: the window's class
NEW_FILE_EXAMPLE "docs/notes.md": the example the New file dialog shows
editors(), open_file(path) (async), discard_editor(window) EditorMixin's when you have it, else the desktop's EditorWindows (see The Editor)
go_to_member(window, member) selects the member's start to end offsets in the file's editor
paths_moved(old, new) editors follow; extend it with super() for what else follows a file
extra_local_items(tree), async extra_local_action(tree, command) your own local menu items, after the explorer's, and what one does
after_tree_action(tree, action) nothing: an operation ended ("rename", "delete"...), the files may have changed
explorer_cursor_moved(tree) nothing: the bar moved (show tree.hint(), the path...)

Add an item of your own to the local menu:

from textual_vision.constants import Command
from textual_vision.menus import MenuItem

CM_RUN_FILE = Command.USER + 20


class Workbench(ExplorerMixin, DesktopApp):
    def extra_local_items(self, tree):
        path = tree.selected_path
        return [MenuItem("~R~un", CM_RUN_FILE, disabled=path is None or path.suffix != ".py")]

    async def extra_local_action(self, tree, command: int) -> None:
        if command == CM_RUN_FILE:
            await self.run_script(tree.selected_path)    # yours

The local menu's own commands are CM_TREE_OPEN to CM_TREE_MOVE (FRAMEWORK_COMMANDS[2..11], see Application Mixins). With GitMixin, the tree shows git's marks and the window's bottom border the branch (see Git and Diffs).

The local menu, for any window

turboframe.ui.localmenu is Borland's local menu on its own: Alt+F10, or a right click, on a view opens a menu of what can be done with what is under its bar, at that place on the screen.

from textual_vision.menus import Menu, MenuItem

from turboframe.ui.localmenu import pop_local_menu

command = await pop_local_menu(app, Menu([MenuItem("~O~pen", CM_OPEN, "Enter"),
                                          MenuItem("~D~elete", CM_DELETE, "Del")]), (x, y))
if command == CM_OPEN:                      # None: closed with Esc or a click outside
    ...
  • pop_local_menu(app, menu, at), from a worker, shows menu at the screen position at and returns the command chosen, or None.
  • LocalMenu(menu, at) is the modal screen behind it, with Turbo Vision's shadow; it moves the menu to stay on the screen (above the place when there is no room below).
  • It answers only with the commands of the menu's enabled items (menu_commands(menu)), so any window can have one.

API: turboframe.ui.explorer, turboframe.ui.localmenu.

Clone this wiki locally