Repository navigation
Application Mixins
TurboFrame's larger features are mixins: classes you list before DesktopApp in your application's bases. Each brings a feature's flows (its dialogs, its windows, what it does with the files) and asks your application for the rest through hooks with defaults. The keys and the menus stay yours.
| Use it for | composing an editor, an explorer, git, a language server, a palette and a language menu in one desktop |
| Import | each mixin from its module (below) |
| Needs | the lsp extra for LspMixin; the watch extra for the explorer to follow outside changes |
| Extend | override a hook; extend a cooperative hook with super()
|
| Mixin | Module | Gives | Guide |
|---|---|---|---|
ColorsMixin |
turboframe.ui.colors |
Options > Colors: choose_colors(). Already part of DesktopApp
|
Themes and Colors |
EditorMixin |
turboframe.ui.editing |
New, Open, Save, Save as, Save all, Close, Go to line, goto_location
|
The Editor |
SearchMixin |
turboframe.ui.searching |
Find, Replace, Search again in the active editor | Search |
FindInFilesMixin |
turboframe.ui.findfiles |
Find in files and its results window | Search |
LspMixin |
turboframe.ui.lsp |
a language server in the editors: completion, signatures, hovers, definitions, references, problems (lsp extra) |
The Editor, LSP Helpers |
ExplorerMixin |
turboframe.ui.explorer |
the project tree and its file operations | The Explorer |
GitMixin |
turboframe.ui.git |
the Git menu, its windows, the explorer's marks, the editors' gutter marks | Git and Diffs |
PaletteMixin |
turboframe.ui.palette |
Go to file and the command palette | Command Palette |
LanguageMixin |
turboframe.ui.language |
Options > Language | Languages |
Put the mixins first and DesktopApp last. Python looks a method up from left to right (the class's MRO), so a mixin's method is found before DesktopApp's.
class Workbench(PaletteMixin, LanguageMixin, GitMixin, LspMixin, FindInFilesMixin, SearchMixin,
EditorMixin, ExplorerMixin, DesktopApp):
...Any order of the mixins works, because they are written to cooperate:
-
The editors belong to
EditorMixin.ExplorerMixinandGitMixinhave their owneditors(),open_file(path)anddiscard_editor(window)for an application withoutEditorMixin; when it is there, they defer to it, before or after it in the bases. -
The editor's events reach every mixin.
after_open,after_save,after_close,editor_changedandcursor_movedare cooperative: each implementation callssuper(), then does its own part.LspMixintells the server;GitMixinmarks the changed lines again. -
Find and Find in files share their text.
SearchMixinandFindInFilesMixinkeep the last text and options in the same attributes (search_text,search_options).
What each needs:
| Mixin | Needs |
|---|---|
LspMixin |
EditorMixin (its editor_for, active_editor, goto_location), an EDITOR_WINDOW whose editor's SMART_LANGUAGES names the language |
GitMixin |
a folder in a repository; ExplorerMixin for the tree's marks and the branch on its border (optional) |
PaletteMixin |
a folder for Go to file; an open_file(path) (EditorMixin's) |
SearchMixin |
editor windows (EditorMixin's active_editor(), or the active window's editor) |
ExplorerMixin, FindInFilesMixin
|
a folder
|
folder is an attribute of your application (a Path, or None while nothing is open). Every mixin's default hooks read it.
When you extend one of these, call super() first, so the mixins hear it too:
| Hook | Called when | Implemented by |
|---|---|---|
after_open(window) |
an editor window is on the desktop, its file read (or untitled) |
EditorMixin, LspMixin
|
after_save(window) |
its text was written to window.path (maybe a new one: Save as) |
EditorMixin, LspMixin
|
after_close(window) |
it was closed (window.path still says which file) |
EditorMixin, LspMixin
|
editor_changed(window) |
its text changed |
EditorMixin, LspMixin, GitMixin
|
cursor_moved(window) |
its cursor or selection moved |
EditorMixin, LspMixin
|
def after_save(self, window) -> None:
super().after_save(window) # the language server and the others first
self.hint(f"Saved {window.display_name}")Several mixins also call methods your application may have:
| Your method | Called by | When |
|---|---|---|
update_status() |
EditorMixin, LspMixin, GitMixin
|
after a save, a server's state or a repository's state changed: refresh your status line |
goto_location(path, start, end) |
LocationsWindow and its subclasses |
Enter on a result (EditorMixin gives one) |
request_close(window) |
an editor's and the explorer's close icon | (EditorMixin gives one: it asks about unsaved changes) |
A menu item, a status item, a key or your code posts a CommandMessage. Each mixin gives an async dispatcher that runs its own commands and says whether it did. They show dialogs, so call them from a worker:
| Dispatcher | Runs | Returns |
|---|---|---|
editor_command(command, info=None) |
EDITOR_COMMANDS: textual-vision's Command.NEW, OPEN, SAVE, SAVE_AS, SAVE_ALL, CLOSE, and CM_GOTO_LINE. info: a Path for Open, a window for Close |
True when it ran it |
search_command(command) |
SEARCH_COMMANDS: CM_FIND, CM_REPLACE, CM_SEARCH_AGAIN
|
True when it ran it |
lsp_command(command, info=None) |
LSP_COMMANDS: CM_LSP_DEFINITION, CM_LSP_REFERENCES, CM_LSP_HOVER, CM_LSP_BACK, CM_LSP_PROBLEMS, CM_LSP_RESTART
|
True when it ran it |
palette_command(command) |
PALETTE_COMMANDS: CM_GOTO_FILE, CM_COMMANDS
|
True when it ran it |
language_command(command) |
CM_LANGUAGE |
True when it ran it |
git_command(command) |
GIT_COMMANDS, those GIT_FEATURES offers (the others do nothing) |
True when the command is Git's (since v0.2.1; v0.2.0 returned None) |
Some features have no command of TurboFrame's: number your own and call the method. find_in_files(), choose_colors(), choose_language(), show_explorer(), palette(), close_all().
@work(group="command")
async def run_command(self, command: int, info: object = None) -> None:
if not (await self.git_command(command) or await self.editor_command(command, info)
or await self.search_command(command) or await self.lsp_command(command, info)
or await self.palette_command(command) or await self.language_command(command)):
... # your own commandsYour commands are numbered from Command.USER (see The Desktop). TurboFrame's own are in FRAMEWORK_COMMANDS (Command.USER + 10000 to + 10999, in turboframe.ui.desktop), so they never clash with yours. check_commands(yours) raises ValueError for one of yours in that range, or two equal.
FRAMEWORK_COMMANDS[...] |
Module | Commands |
|---|---|---|
0, 1
|
ui.dialogs |
CM_CHANGE_ALL (Replace's Change all, the prompt's All), CM_BROWSE (an input dialog's Browse) |
2 to 11
|
ui.explorer |
CM_TREE_OPEN, CM_TREE_NEW_FILE, CM_TREE_NEW_FOLDER, CM_TREE_RENAME, CM_TREE_DELETE, CM_TREE_REFRESH, CM_TREE_CUT, CM_TREE_COPY, CM_TREE_PASTE, CM_TREE_MOVE: the local menu's |
12 to 21
|
ui.git |
the Git menu: CM_GIT_CHANGES, CM_GIT_HISTORY, CM_GIT_BRANCHES, CM_GIT_COMMIT, CM_GIT_PULL, CM_GIT_PUSH, CM_GIT_FETCH, CM_GIT_DIFF_FILE, CM_GIT_FILE_HISTORY, CM_GIT_BLAME
|
22 to 37
|
ui.git |
the Git windows' local menus: stage, discard, amend, switch, branches, merge, stash... |
38 |
ui.editing |
CM_GOTO_LINE |
39 to 41
|
ui.searching |
CM_FIND, CM_REPLACE, CM_SEARCH_AGAIN
|
42 to 47
|
ui.lsp |
CM_LSP_DEFINITION, CM_LSP_REFERENCES, CM_LSP_HOVER, CM_LSP_BACK, CM_LSP_PROBLEMS, CM_LSP_RESTART
|
48, 49
|
ui.palette |
CM_GOTO_FILE, CM_COMMANDS
|
50 |
ui.language |
CM_LANGUAGE |
The rest of the range is kept for TurboFrame's next components. The File commands (New, Open, Save...) are textual-vision's own Command values.
The mixins bind no application keys, and build no menu bar except the Git menu (git_menu_items()). You choose the keys, write the menus, and route both to your command worker. The windows keep their own keys: the explorer's Ins, F2 and Del, the Git windows' Space and Ctrl+K, the editor's Ctrl+Space.
A Textual binding can post any command. A MenuItem's key text ("F3") is only shown: give the key a binding as well.
def key(binding: str, command: int) -> Binding:
return Binding(binding, f"cmd({int(command)})", show=False, priority=True)
class Workbench(...):
BINDINGS = [key("f3", Command.OPEN), key("ctrl+f", CM_FIND), key("ctrl+p", CM_GOTO_FILE)]
def action_cmd(self, command: int) -> None:
if not self.dialog_open(): # a dialog has the keys
self.post_message(CommandMessage(command))Every mixin in one desktop. It needs the lsp and watch extras, and a language server for the editors (here pyright) on the PATH.
"""Workbench: a code editor's desktop."""
from __future__ import annotations
import sys
from pathlib import Path
from textual import work
from textual.binding import Binding
from textual_vision.constants import Command
from textual_vision.events import CommandMessage
from textual_vision.menus import Menu, MenuItem, Separator, SubMenu
from textual_vision.status_line import StatusDef, StatusItem
from turboframe.config import JsonStore
from turboframe.i18n import Domain, choose_language
from turboframe.lsp.session import ServerSpec
from turboframe.recent import Recent
from turboframe.ui import history
from turboframe.ui.app import DesktopApp
from turboframe.ui.desktop import check_commands
from turboframe.ui.diffview import DiffView
from turboframe.ui.editing import CM_GOTO_LINE, EditorMixin
from turboframe.ui.editor import CodeEditor, EditorWindow
from turboframe.ui.explorer import ExplorerMixin
from turboframe.ui.findfiles import FindInFilesMixin
from turboframe.ui.git import GIT_COMMANDS, GitMixin
from turboframe.ui.language import CM_LANGUAGE, LanguageMixin
from turboframe.ui.lsp import CM_LSP_BACK, CM_LSP_DEFINITION, CM_LSP_PROBLEMS, CM_LSP_REFERENCES, LspMixin
from turboframe.ui.palette import CM_COMMANDS, CM_GOTO_FILE, PaletteMixin
from turboframe.ui.searching import CM_FIND, CM_REPLACE, CM_SEARCH_AGAIN, SearchMixin
# your settings, and the components that keep theirs there
SETTINGS = JsonStore("workbench")
history.set_store(SETTINGS)
DiffView.store = SETTINGS
# your texts, and TurboFrame's, in the language chosen
DOMAIN = Domain("workbench", Path(__file__).parent / "locale")
_ = DOMAIN.gettext
# your own commands: from Command.USER, never in TurboFrame's range
CM_FIND_IN_FILES = Command.USER + 1
CM_COLORS = Command.USER + 2
check_commands([CM_FIND_IN_FILES, CM_COLORS])
PYRIGHT = ServerSpec("pyright", ("pyright-langserver", "--stdio"), language="python")
class PythonEditor(CodeEditor):
SMART_LANGUAGES = frozenset({"python"}) # files a language server serves
class PythonWindow(EditorWindow):
EDITOR = PythonEditor
def key(binding: str, command: int) -> Binding:
return Binding(binding, f"cmd({int(command)})", show=False, priority=True)
class Workbench(PaletteMixin, LanguageMixin, GitMixin, LspMixin, FindInFilesMixin, SearchMixin,
EditorMixin, ExplorerMixin, DesktopApp):
TITLE = "Workbench"
EDITOR_WINDOW = PythonWindow
LSP_SERVERS = (PYRIGHT,)
colors_store = language_store = lsp_store = SETTINGS
language_domain = DOMAIN
BINDINGS = [
key("f2", Command.SAVE), key("f3", Command.OPEN), key("alt+f3", Command.CLOSE), key("alt+x", Command.QUIT),
key("ctrl+f", CM_FIND), key("ctrl+r", CM_REPLACE), key("ctrl+l", CM_SEARCH_AGAIN),
key("shift+f2", CM_FIND_IN_FILES), key("ctrl+g", CM_GOTO_LINE),
key("f12", CM_LSP_DEFINITION), key("shift+f12", CM_LSP_REFERENCES), key("alt+left", CM_LSP_BACK),
key("ctrl+p", CM_GOTO_FILE), key("alt+p", CM_COMMANDS),
]
def __init__(self, folder: Path) -> None:
super().__init__() # reads colors_store: set it before, as a class attribute here
self.folder = Path(folder).resolve()
self.recent = Recent(SETTINGS)
self.recent.add("folders", self.folder)
# ---------------------------------------------------------------- the bars
def init_menu_bar(self) -> Menu:
return Menu([
SubMenu(_("~F~ile"), MenuItem(_("~N~ew"), Command.NEW), MenuItem(_("~O~pen..."), Command.OPEN, "F3"),
MenuItem(_("~S~ave"), Command.SAVE, "F2"), MenuItem(_("Save ~a~s..."), Command.SAVE_AS),
MenuItem(_("Save a~l~l"), Command.SAVE_ALL), Separator(),
MenuItem(_("~G~o to file..."), CM_GOTO_FILE, "Ctrl+P"),
MenuItem(_("Co~m~mands..."), CM_COMMANDS, "Alt+P"), Separator(),
MenuItem(_("E~x~it"), Command.QUIT, "Alt+X")),
SubMenu(_("~S~earch"), MenuItem(_("~F~ind..."), CM_FIND, "Ctrl+F"),
MenuItem(_("~R~eplace..."), CM_REPLACE, "Ctrl+R"),
MenuItem(_("~S~earch again"), CM_SEARCH_AGAIN, "Ctrl+L"),
MenuItem(_("F~i~nd in files..."), CM_FIND_IN_FILES, "Shift+F2"), Separator(),
MenuItem(_("~G~o to line..."), CM_GOTO_LINE, "Ctrl+G"),
MenuItem(_("Go to ~d~efinition"), CM_LSP_DEFINITION, "F12"),
MenuItem(_("Find re~f~erences"), CM_LSP_REFERENCES, "Shift+F12"),
MenuItem(_("~P~roblems"), CM_LSP_PROBLEMS)),
SubMenu(_("~G~it"), *self.git_menu_items()),
SubMenu(_("~O~ptions"), MenuItem(_("~C~olors..."), CM_COLORS),
MenuItem(_("~L~anguage..."), CM_LANGUAGE)),
])
def init_status_line(self) -> list[StatusDef]:
return [StatusDef(0, 0xFFFF, [StatusItem(_("~F2~ Save"), "f2", Command.SAVE),
StatusItem(_("~F10~ Menu"), "f10", Command.MENU),
StatusItem(_("~Alt+X~ Exit"), "alt+x", Command.QUIT)])]
# ---------------------------------------------------------------- start
def on_mount(self) -> None:
self.call_after_refresh(self.start)
def start(self) -> None:
self.show_explorer()
self.start_git_watch()
# ---------------------------------------------------------------- the hooks you extend
def after_open(self, window) -> None:
super().after_open(window) # cooperative: the language server and git hear it too
if window.path is not None:
self.recent.add("files", window.path)
# ---------------------------------------------------------------- commands
def action_cmd(self, command: int) -> None:
if not self.dialog_open():
self.post_message(CommandMessage(command))
def on_command_message(self, message: CommandMessage) -> None:
message.stop()
message.prevent_default() # Command.QUIT is yours: unsaved editors first
if message.command != Command.VALID:
self.run_command(message.command, message.info)
@work(group="command")
async def run_command(self, command: int, info: object = None) -> None:
if command == Command.QUIT:
if await self.close_all():
await self.lsp_shutdown()
self.exit()
elif command == CM_FIND_IN_FILES:
await self.find_in_files()
elif command == CM_COLORS:
await self.choose_colors()
elif command in GIT_COMMANDS:
await self.git_command(command)
elif await self.editor_command(command, info):
pass
elif await self.search_command(command):
pass
elif await self.lsp_command(command, info):
pass
elif await self.palette_command(command):
pass
else:
await self.language_command(command)
def main() -> None:
DOMAIN.use(choose_language(env="WORKBENCH_LANGUAGE", program="workbench", setting=SETTINGS.get("language")))
Workbench(Path(sys.argv[1]) if len(sys.argv) > 1 else Path.cwd()).run()
if __name__ == "__main__":
main()What it shows:
-
Settings first. One
JsonStorefor everything (see Settings and Recent Files).colors_storeis a class attribute becauseDesktopApp.__init__reads it. -
The language before the texts.
main()chooses the language before the application is made, so the menus are built in it (see Languages). Without alocalefolder, the domain is English. -
on_command_messagestops every command and hands it to one worker.Command.QUITcloses the editors first (asking about unsaved changes), stops the language servers, then exits. -
on_mountonce. Textual callson_mounton every class of the hierarchy, soDesktopApp's still runs (see The Desktop).
Test it with Textual's Pilot, as Testing shows: isolated_config keeps the JsonStore away from your own settings.
API: turboframe.ui.editing, turboframe.ui.searching, turboframe.ui.findfiles, turboframe.ui.lsp, turboframe.ui.explorer, turboframe.ui.git, turboframe.ui.palette, turboframe.ui.language, turboframe.ui.colors, turboframe.ui.app, turboframe.ui.desktop.
TurboFrame · part of Divengine · GPL-3.0-or-later · report an issue
Tutorial
Examples
The desktop
- The Desktop
- Application Mixins
- Windows and Lists
- Dialogs
- Histories
- Progress
- Themes and Colors
- Glyphs
- Settings and Recent Files
- Command Palette
Editing
Tasks
Languages
Running
Reference
Links