Skip to content

Settings and Recent Files

rafageist edited this page Dec 2, 2026 · 2 revisions

Settings and Recent Files

Your application keeps its settings in one place, a store. TurboFrame's components keep theirs there too: the histories, the theme, the language, the recent files, the diff layout. You give them the store once, when your application starts.

Use it for the user's settings, kept between runs; the folders and files opened lately
Import from turboframe.config import JsonStore, config_home, from turboframe.recent import Recent
Needs nothing beyond TurboFrame
Extend any object with load() and save(dict) is a store

The store protocol

A store is any object with two methods:

Method
load() -> dict the settings, as a dict (an empty one when there are none)
save(data: dict) keep data whole; raise OSError when it cannot

Each component reads the whole dict, changes its own key, and saves the whole dict. So one store holds everything, and your own keys sit beside TurboFrame's.

Key Written by Holds
"history" turboframe.ui.history (see Histories) each input line's history, and the palette's recent commands ("commands")
"palette", "colors" Options > Colors (DesktopApp.colors_store, see Themes and Colors) the theme and the colour depth
"language" Options > Language (LanguageMixin.language_store, see Languages) the interface language, from the next start
"recent" Recent (below) the folders and files opened lately
"git_diff_side_by_side" DiffView.store (see Git and Diffs) unified or side by side
"lsp", "lsp_commands" read by LspMixin.lsp_store (see The Editor) a server per language, a server's command line

JsonStore: a JSON file of the user's

JsonStore(app, file="config.json", *, appdata=True) is the file <config home>/<app>/<file>:

Platform Config home (config_home())
Linux $XDG_CONFIG_HOME, else ~/.config
Windows $XDG_CONFIG_HOME, else %APPDATA%; with appdata=False, ~/.config
from turboframe.config import JsonStore

settings = JsonStore("myapp")      # ~/.config/myapp/config.json, %APPDATA%\myapp\config.json
print(settings.path)               # computed on each use: a test may change XDG_CONFIG_HOME
data = settings.load()             # {} for a missing, unreadable or malformed file
settings.save({**data, "tab_size": 4})
settings.get("tab_size", 8)        # one key
settings.set_value("tab_size", 2)  # one key; a read-only home keeps nothing and says nothing
  • A save writes a temporary file next to the target, then replaces it: an interrupted save leaves the old settings whole.
  • A file that is not JSON, or whose top level is not an object, loads as {}.
  • save raises OSError when the folder cannot be written. TurboFrame's components catch it and say so in a notification; set_value ignores it.
  • appdata=False keeps an application's settings in ~/.config on Windows too, where its users already have them.

Plugging the store in

Give each component the same store, once, before your application starts:

from turboframe.config import JsonStore
from turboframe.ui import history
from turboframe.ui.app import DesktopApp
from turboframe.ui.diffview import DiffView
from turboframe.ui.language import LanguageMixin

SETTINGS = JsonStore("myapp")
history.set_store(SETTINGS)        # every HistoryInput
DiffView.store = SETTINGS          # every DiffView: unified or side by side


class MyApp(LanguageMixin, DesktopApp):
    colors_store = SETTINGS        # DesktopApp reads it in __init__: set it before super().__init__()
    language_store = SETTINGS

colors_store is read when DesktopApp starts, to choose the theme. Set it as a class attribute, or on self before super().__init__().

Recent folders and files

Recent(store, key="recent", *, limit=12, kinds=("folders", "files")) keeps a list of paths per kind, newest first, under the store's "recent":

from turboframe.recent import Recent

recent = Recent(SETTINGS)
recent.add("files", Path("src/app.py"))   # first in its list, once, resolved
recent.entries("files")                   # [Path(...), ...]: those still on disk, newest first
recent.forget("files", path)              # out of the list, as entries() gave it
recent.add("projects", path)              # ValueError: an unknown kind
  • entries leaves out a path that no longer exists (a folder that is no longer a folder, a file that is no longer a file). The stored list keeps it until it is pushed out or forgotten.
  • limit is per kind (LIMIT, 12, by default). kinds names your own lists: Recent(SETTINGS, kinds=("folders", "files", "databases")).
  • A store that cannot save keeps nothing and says nothing: a recent list is not worth an error.

Feed it from the editor's cooperative hook, and offer it in a menu. A menu item's param reaches your command handler as message.info, so Command.OPEN with a path opens that file through EditorMixin.editor_command (see Application Mixins):

class MyApp(EditorMixin, DesktopApp):
    def __init__(self) -> None:
        super().__init__()
        self.recent = Recent(SETTINGS)

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

    def init_menu_bar(self) -> Menu:
        reopen = [MenuItem(path.name, Command.OPEN, param=path) for path in self.recent.entries("files")]
        return Menu([SubMenu("~F~ile", MenuItem("~O~pen...", Command.OPEN, "F3"),
                             *([SubMenu("~R~ecent", *reopen)] if reopen else []),
                             Separator(), MenuItem("E~x~it", Command.QUIT, "Alt+X"))])

The menu bar is built when the application starts, so it lists the files of the last session. The command palette lists the menus' items, so the recent files are there too (see Command Palette).

In tests

MemoryStore (turboframe.ui.history) is a store in memory: a dict, for the session. Give it to components in tests, or for settings that should not be kept:

from turboframe.ui.history import MemoryStore

async def test_starts_in_the_kept_theme(monkeypatch):
    store = MemoryStore()
    store.save({"palette": "modern-dark"})              # start with what the test needs
    monkeypatch.setattr(MyApp, "colors_store", store)   # before the app is made: __init__ reads it
    app = MyApp()
    async with app.run_test():
        assert app.theme == "modern-dark"

To test with a real JsonStore without touching the user's files, use the isolated_config fixture: it points XDG_CONFIG_HOME (and APPDATA on Windows) at a temporary folder (see Testing).

API: turboframe.config, turboframe.recent, turboframe.ui.history.

Clone this wiki locally