Architecture¶
This page explains how the core and the backends work together to render views and handle events.
Project layout¶
src/composeui/
cli.py # the `composeui` command (`composeui run app.py`, `composeui translations`)
core/ # toolkit-agnostic: views, signals, renderer base, application, registry
_views/ # the views, a module per family (view.py exports them)
qtcore/ # Qt backend via qtpy (QtApplication, qtrenderer.py, custom widgets/)
_renderers/ # its renderers, a module per family (renderers.py maps their keys)
textualcore/ # Textual (TUI) backend
_renderers/ # its renderers, a module per family (renderers.py maps their keys)
webcore/ # Web backend (Starlette + htmx + daisyUI); static/app.css is built
_renderers/ # its renderers, a module per family (renderers.py maps their keys)
css/ # source of webcore/static/app.css (`make css`; tools land in css/vendor/)
js/ # the scripts' type check (`make js-check`; TypeScript lands in js/vendor/)
specs/ # TLA+ specs, checked by everystate (`make specs`; it lands in specs/vendor/)
src/examples/ # example apps (pipeform.py, pipecatalogue.py, ...), also used by tests; not in the wheel
tests/ # pytest suite (pytest-qt, pytest-asyncio, Textual run_test pilot)
qtcore/ # the Qt backend's tests, a module per family, as in _renderers/
textualcore/ # the Textual backend's tests, a module per family, as in _renderers/
webcore/ # the web backend's tests, a module per family or per other webcore module
contracts/ # the rules every backend follows, each test run on each backend
docs/ # the user guide (user-guide/), the examples guide, this guide, the Sphinx site
The core imports no backend¶
Importing composeui.core does not load Qt, Textual, or the web backend. When an app calls
run, it imports the application module for the selected backend before starting the app.
When a view needs a renderer, the registry imports the renderers module for that backend.
tests/test_renderer_registry.py checks that importing composeui.core.view loads no toolkit.
The registry¶
composeui.core.registry maps renderer keys to the renderers of each backend:
Each
RendererTypemember is a backend. Its value is aBackend, which holds:renderers: the dotted path of the module that exposes theRENDERERSmapping,dict[str, Callable[[Any], Renderer]];applications: the dotted path of the module that exposesAPPLICATIONandMODEL_APPLICATION, the application classes thatcore.application.runstarts;extraandpackages: the extra of the package that installs the backend’s dependencies, and their top-level modules. When the backend’s import fails and one of these modules is missing,runstops and names the extra.
A view names its renderer with its
_renderer_keyclass variable, for example"label". A view of another package sets it withdefine_view(renderer_key=...).create_renderer(renderer_type, key, view)imports the renderers module of the backend and looks up the key. When the backend does not register the key, it looks for it in the package that the key’s first part names, through thecomposeui.renderersentry points (see Add a widget from another package). When no package registers the key either, it returnsNoneand logs a warning once per backend and key. The backend leaves the view out.A renderer for the
"router"or"tabs"key can setrenders_on_demand = True.RouterandTabViewread this flag withrenders_on_demand(renderer_type, key). With this flag, the backend waits until a page or tab is first shown to render its content. Its navigation entry and dialogs are available before then. Qt and the web use this mode. Textual renders the content of every page and tab up front. See Pages, tabs, and dialogs for the web backend.
The three backends register the same keys, except for maps, which Textual omits, and meshes,
which only Qt draws.
test_every_backend_registers_the_same_renderer_keys_except_graphical_views checks this contract.
Views and renderers¶
The views are the view-models of MVVM, and the toolkit objects are the views. The renderers are the binding between them. See How ComposeUI maps to MVVM.
A view is an attrs class. @define_view adds the notify_renderer hook to the
on_setattr of its fields. When code sets a public attribute to a new value, the hook calls
refresh_attribute(name, value) on the renderer of the view. Do not add manual update()
or refresh() calls.
composeui.core.view is the public module of the views: it imports them and lists them in
__all__, and its last line sets up the Shape union, once every class it needs exists. Each
family of views has its module in core/_views/, as the three backends’ renderers do: inputs.py,
controls.py, choices.py, content.py, charts.py, graphics.py, tables.py, files.py,
forms.py, actions.py, dialogs.py, containers.py and navigation.py. base.py holds
View, define_view, the lazy signals, the converter CONVERTER and the helpers that several
families share. main.py holds MainView and the state code, which treats some views apart
(choices, record tables, charts): it imports any family, and no family imports it at run time.
The base names no concrete view: a walk of the views calls a method that View defines, such
as _check_again (a check run again in a new language) and _keep_model (a list’s model).
View._main_view names MainView, which attrs resolves in base.py: main.py puts it there.
Qt uses the same families in qtcore/_renderers/. qtrenderer.py holds the base
QtWidgetRenderer, the shared main-thread invoker, type variables and the widget-size constant.
renderers.py only maps keys to renderer classes. Family modules import each other directly,
not through that mapping. forms.py owns _widget_of and the single form-row widget cache.
containers.py owns the shared layout and dialog-parent helpers. navigation.py holds the
main renderer, window, router and sidebar. graphics.py loads maprenderer.py only when a
map is rendered. An app without maps does not load Qt Quick. When you move a renderer,
preserve signal order, dialog state, and on-demand rendering of pages and tabs.
Textual uses the same families in textualcore/_renderers/. textualrenderer.py holds the
base TextualWidgetRenderer and shared thread and mount helpers, including _refresh_tree.
renderers.py only maps keys to renderer classes. The family modules import each other
directly, not through that mapping. forms.py owns _widget_of and the form-row widget cache,
so layouts and dialogs share one widget per row. actions.py keeps _ComposeUIApp beside
the actions: the app dispatches their events and manages their key bindings. This also keeps
the toolbar’s app check and the app’s action-renderer check in one module, without a cycle.
navigation.py holds the main renderer, router and sidebar. When you move a renderer,
preserve mount order, worker dispatch, and dialog state.
A renderer (composeui.core.renderer.Renderer) binds a view to a toolkit object, its
rendered object. It syncs them in both directions:
Method |
Direction |
Does |
|---|---|---|
|
view to toolkit |
Creates the rendered object. |
|
view to toolkit |
Calls every handler of |
|
view to toolkit |
Calls the handler of one attribute. |
A handler of a widget signal, connected in |
toolkit to view |
Sets the view attribute inside |
_refresh_dispatcher maps each view attribute that the renderer cares about to its
handler. When a view attribute changes and it has no handler,
refresh_attribute raises MissingRefreshAttributeFunctionError.
Inside stop_refresh(), is_updating_state() is true. notify_renderer then does not
refresh the toolkit with the values that came from it.
call_on_main_thread(callback) calls the callback directly by default. Each backend of this
repo overrides it: Qt and Textual run the callback on their main thread, and the web runs it
under the session’s lock. See A button click.
Signals¶
Signal.connect and Application.connect read the parameter names of a callback:
Signal.connectinjectsview, the view that owns the signal, and the app’smain_viewandmodelwhen the callback asks for them. The callback gets only as many of the signal’s arguments as it takes.Application.connectsupplies its explicitview, which need not own the signal.
These names are part of the API: keep them exact.
A view makes each of its signals on the first read of its field, as most are never connected.
define_view gives each field whose default makes a signal a _LazySignal. A web session’s page
has views by the hundred, so the signals that nothing reads cost nothing. A view keeps the
signals made in its _signals. A signal made after set_references gets the main view and the
model as it is made. _LazySignal gives each signal a weak reference to its owning view,
also when code supplies the signal. Callbacks connected before the signal is assigned to a
view get that owner too. A view refuses a signal that another live view owns, so a
callback’s view never changes. Code that walks a view’s fields uses view_fields,
which leaves the signals out. The core emits a signal that often has no callback, such as
checked, with emit_if_made.
test_a_session_makes_only_the_signals_something_connects fails if a walk reads them all.
Callback registration and owner assignment share a lock. connect prepares the callback
outside the lock, then gives it the current owner and registers it inside the lock.
This prevents a concurrent owner assignment from leaving the callback with an old owner.
Callbacks run outside the lock, including the immediate call from now=True.
Reactive methods¶
composeui.core.reactivity runs the reactive methods of the
views. The diagram follows show_total from that guide’s order example, with delivery unchecked.
Field tracking starts with the first @reactive method or the first call to a helper that follows
its inputs:
The view classes wait.
@define_viewregisters each view class. When field tracking starts, ComposeUI sets up the registered classes. It sets up later classes as they register.A field gets a descriptor. A tracked class gets a
_FieldReaderfor each public field except signals andrenderer. It wraps the__setattr__thatattrsgives it. The values stay in the instance’s__dict__(slots=False).Reads need no descriptor outside a batch.
_FieldReaderhas neither__get__nor__set__then, so reads take the value directly from__dict__._recording_readsinstalls both methods and uses a counter under a lock to remove them when the last batch in any thread ends.__get__records the read only if_TRACKINGholds a reaction in the current context.Writes take a short path when possible. If no method has read a view’s fields and the current context is not tracking reads, the wrapper calls the normal setter without checking for changed inputs. It still handles child views that enter or leave the field. Otherwise
_set_watchedrefuses a write if the running method already read that field. It runs the field’s hooks without tracking their reads, then tells the readers if the value changed._FieldReader.__set__only stores the value. Useset_valueto tell the readers about a write that bypasses the field’s hooks.Batches.
batch()holds the methods to run in the_PENDINGcontext variable, and runs them when the outermost batch ends.Signal.emit,Renderer.stop_refresh, the web session’s handling of an event, New and Open (_apply_state,_reset_state), andstart_reactionsopen one.A fixed order. Each
_Reactiontakes a number when it starts._run_allruns the waiting reactions by that number, from a heap. If a reaction needs a 101st run in one batch,_run_allstops the batch withReactiveLoopError. Otherwise, when a method fails, the waiting methods still run._run_allraises the first exception and logs any others.No leaks. A
Sourceholds its readers by weak key, and a_Reactionits view by weak reference. An ended web session callsstop_reactionson its main view.Tasks. A
Taskhas aSourcetoo. Reading its state records it, itschangedsignal callsSource.changed, andstart,start_latest, andcancelcallcheck_change.
tests/test_reactivity.py tests each of these rules.
View state¶
MainView.save_state and MainView.load_state serialize the view tree with the cattrs
converter CONVERTER of composeui.core.view. A new view field must stay serializable, or
be excluded:
Fields of the types in
_OMITTED_TYPES(Signal,Renderer,RendererContainer,threading.Timer) are skipped automatically.Other fields that cannot be serialized, such as
Validatorfields, take theOMITmetadata key.A field that a study leaves out but a session keeps, such as the tab shown, takes
SESSIONwithOMIT.save_reloaded_statesaves these fields apart from the study (session_data), for a reload and for an idle web session. A view whose content no field holds, such as a console’s lines and their styles, gives it inView._session_content, and shows it again inView._load_session_content.session_datawalks the views of fields only, not those of a list such as aListView’s: the web keeps a session in memory while those show what it would lose.Text that the app’s code sets, not the user, takes the
UI_TEXTmetadata key. See Saving and loading state.
Temporary files and the exit¶
A folder per process.
scratch_directory(core/_files.py) gives each process a folder incomposeui-scratch-<uid>(composeui-scratchon Windows), in the system’s temporary folder. The SQLite model’s scratch databases, a study’s temporary files, the web’s uploads and idle sessions, and a reload’s state go in it. The process holds a SQLite lock on itslock.sqlitewhile it runs. The operating system releases the lock however the process ends.A start removes a crash’s files.
Applicationremoves the folders that no process holds. It leaves a folder younger than a minute: its process locks it only once it made it. When another user ownscomposeui-scratch-<uid>, or may write in it, or a file is at its path, the process uses a folder ofmkdtempinstead, which no start removes. A file that another user puts at that path doesn’t stop the app.Unfinished files beside the user’s.
partial_pathnames a file beside its destination, renamed over it once complete. It first records the file’s path in the process’s folder. A start removes the files that an abandoned folder records.A reload’s child holds its supervisor’s folder (
hold_scratch). If the supervisor is killed first, the child’s files stay until the child ends.The exit waits for the writes. A connection closed during another thread’s statement crashes the process. Each database of the SQLite model counts the turns and the readers that use it. At Python’s exit,
_close_at_exitrefuses new uses: a job’s thread waits for the process’s end, and the main thread getsRefusedError. Both are refused outside the model’s locks (_refuse_at_exit): a job’s thread that waits holds no lock that the main thread needs. The exit waitsEXIT_WAIT_SECONDSfor the uses to end. It then interrupts the statements left, on the turns’ connection and on the readers’ connections, and waitsINTERRUPTED_WAIT_SECONDS. It then closes each database that no thread uses, and that no other thread still running made. Python runs theweakreffinalizers before: a database’s finalizer is kept off Python’s exit, and a close detaches it to run it. A web server that stops waits in the same way for the databases of the sessions that it closed (wait_for_closed_writes): uvicorn ends without Python’s exit.