Phosphor
Qt6 / Wayland library suite for window-management tools
Loading...
Searching...
No Matches
phosphor-config

Pluggable configuration backends: JSON-on-disk or a custom IBackend, with a schema-validated Store and a versioned migration runner.

Responsibility

Structured settings addressed by (group, key), where the group name may be flat (General) or dot-path (Snapping.Behavior.ZoneSpan), with typed values (bool, int, double, color, string, map, list), defaults, and validation. The library provides:

  • A Store front-end with read<T>(group, key), readVariant(group, key), and write(group, key, value) over a pluggable IBackend. The library ships JsonBackend, and tests can supply their own in-memory IBackend.
  • Schema-driven defaults and validation. The Schema declares the groups and, per KeyDef, the default value, optional expected type, and an optional validator applied on both read and write.
  • Versioned migrations. MigrationRunner runs the Schema's MigrationStep chain v1 -> v2 -> v3 ... against the raw JSON root. Each schema-version bump lands one migration step, and consumers never have to write per-key fallback reads.
  • Group-path resolution. An optional IGroupPathResolver on the Schema translates group names into a lookup the backend understands, regardless of whether the backend stores by path or nested object.

Key types

Type Purpose
PhosphorConfig::Store Front-end API: read<T>(), readVariant(), write(), reset(), changed() signal
PhosphorConfig::IBackend Abstract backend. Shipped: JsonBackend
PhosphorConfig::JsonBackend JSON-on-disk, with the path chosen by the consumer (e.g. $XDG_CONFIG_HOME/<app>/config.json). setOverlay() lays read-only in-memory values over the file
PhosphorConfig::QSettingsBackend Read-only reader for a legacy KConfig-style INI file, for migration onto JsonBackend
PhosphorConfig::Schema Declarative struct: groups of KeyDef (default + expected type + validator), version, migration chain
PhosphorConfig::MigrationRunner Runs the schema's MigrationStep chain, one step per schema bump
PhosphorConfig::IGroupPathResolver Group-name to backend-key mapping
PhosphorConfig::HostDirectory Which host's settings file a settings module edits, when several hosts can serve one API: their installed descriptors, the record the running host writes, and the choice between them

Typical use

#include <PhosphorConfig/Store.h>
#include <PhosphorConfig/JsonBackend.h>
#include <PhosphorConfig/Schema.h>

using namespace PhosphorConfig;

// The backend is borrowed: the caller keeps it alive for the store's lifetime.
auto backend = std::make_unique<JsonBackend>(configPath);
Store settings(backend.get(), myAppSchema());   // consumer builds its own Schema

// Read a declared key; the schema default applies when it is unset.
bool zoneSpanEnabled =
    settings.read<bool>(QStringLiteral("Snapping.Behavior.ZoneSpan"),
                        QStringLiteral("enabled"));

// Write. The file is rewritten on the next sync() or commit(), not here.
settings.write(QStringLiteral("Snapping.Behavior.ZoneSpan"),
               QStringLiteral("enabled"), true);

// React to a change. Store::write() and Store::reset() say when one is announced.
connect(&settings, &Store::changed,
        this, [](const QString &group, const QString &key) {
            qDebug() << "changed:" << group << key;
        });

Migrations are declared as MigrationStep entries on the Schema and run by MigrationRunner (one step per schema bump):

// Run once at startup, before opening the backend against the same path.
Schema schema = myAppSchema();
schema.version = 2;
schema.migrations.push_back(MigrationStep{
    .fromVersion = 1,
    .migrate = [](QJsonObject &root) {
        // v1 had a single "snap.enabled" flag; v2 splits into per-edge flags.
        bool was = root.take(QStringLiteral("snap.enabled")).toBool();
        QJsonObject snap;
        snap.insert(QStringLiteral("left"),  was);
        snap.insert(QStringLiteral("right"), was);
        snap.insert(QStringLiteral("top"),   was);
        snap.insert(QStringLiteral("bottom"), was);
        root.insert(QStringLiteral("snap"), snap);
        root.insert(QStringLiteral("_version"), 2);  // each step bumps the version
    },
});

MigrationRunner(schema).runOnFile(configPath);

Command-line style overrides go in an overlay rather than a rewritten file. The overlay has the document's shape, wins over the file for every read (nested objects merge key by key), survives reparseConfiguration(), and is never written back:

// afterglow -o Audio.enabled=false
backend->setOverlay(QJsonObject{
    {QStringLiteral("Audio"), QJsonObject{{QStringLiteral("enabled"), false}}},
});
settings.read<bool>(QStringLiteral("Audio"), QStringLiteral("enabled")); // false

Store's writes, resets and imports decide against the file (IBackend::persistedGroup()), so writing a value equal to the overlay's still persists it.

A file that exists but does not parse, or whose root is not an object, is never overwritten. loadFailed() turns on, the backend reads as the last document it read or wrote cleanly (empty on a first load), and sync(), commit() and applyMigration() refuse rather than write over the user's file. A flush also re-checks the file's size and mtime against the backend's last read or write of it, so a file broken by hand after it was read is refused too. The overlay stays on top of the fallback document. A later reparseConfiguration() or reload() that reads the file cleanly clears the flag. reload() is the same reload for a caller that reports problems itself: it logs nothing and returns the reason the file could not be read. A file that holds only white space reads as an empty document, as a missing one does, and blankFile() tells it from a file that holds {}: an editor that saves in place empties the file before it writes. A caller that reloads at once constructs the backend with JsonBackend::Load::Deferred, so the file is read and reported one time. Until that first reload the backend is empty and refuses writes. A machine-written file with nothing worth keeping opts out with setOverwriteUnreadable(true).

Hosts of a settings API

Some settings can be served by more than one host, each keeping them in its own file. The placement settings are PlasmaZones' on KWin, and the Phosphor compositor is the intended second host, in its own session. A settings module edits the right file whether or not the host runs:

  • Each host's package installs a descriptor, a *.json file in <datadir>/phosphor-works/<api>-hosts/, with its id, name, bus name, backend, config path (starting with $XDG_CONFIG_HOME, $XDG_DATA_HOME, $XDG_STATE_HOME or $HOME) and the desktops it serves. HostDirectory::descriptors() reads them, a per-user one overriding a system one with the same id. Descriptors are keyed by the Id inside the file, and the file name is not checked against it.
  • A host calls writeRecord(id, configPath, pid) when it starts, at $XDG_STATE_HOME/phosphor-works/<api>-host.json. The record stays after the host stops.
  • HostDirectory::resolve() chooses, taking the first of these that applies. The running host's own record: the process that wrote it owns the bus name now, and it wins whatever the desktop. A user's choice: a record with pid 0 whose host serves this session, whether or not anything owns the name. A host's record: one with any other pid, when nothing owns the name and its host serves this session. Then the one descriptor matching XDG_CURRENT_DESKTOP. When several match, it lists them so the module can ask the user and record the answer with pid 0. When none matches, there is no host and nothing to offer.
  • A record's host serves the session when one of the session's desktops is among the descriptor's, ignoring case. A descriptor without Desktops passes that test for a record, but the desktop match never chooses or offers it, so only a record reaches such a host.
  • The file is the record's path as written when a record chose the host, and it is stale if the host has moved its file since. Otherwise it is the descriptor's resolved path.
  • running says only that some process owns the bus name. That process is known to be the chosen host only under the running host's own record.

const PhosphorConfig::HostDirectory hosts(QStringLiteral("placement"));
const QList<PhosphorConfig::HostDescriptor> descriptors = hosts.descriptors();
// resolve() takes the pid of one owner, so the hosts of one API are expected
// to share a bus name and any descriptor's will do. The pid stays 0 when
// nothing owns the name, when no host is installed, or when there is no
// session bus to ask.
qint64 owner = 0;
QDBusConnectionInterface* bus = QDBusConnection::sessionBus().interface();
if (bus && !descriptors.isEmpty()) {
    owner = bus->servicePid(descriptors.constFirst().busName).value();
}
const auto chosen = PhosphorConfig::HostDirectory::resolve(descriptors, hosts.record(), owner,
                                                           PhosphorConfig::HostDirectory::currentDesktops());

Design notes

  • No ad-hoc backwards compatibility. The library enforces one migration per schema bump and nothing else. No per-key fallback reads outside migration functions. Within a schema version, renaming a key means users get the default for the new key, with no silent rescue. This keeps the config-reading code trivial.
  • Per-key validators. Each KeyDef may carry a validator applied on both read and write, giving consumers one place to clamp ranges (qBound), normalize enum-style strings, or fall back to the default on invalid input. Validators must be idempotent so write() can short-circuit no-op saves.
  • Schema carries the defaults. Each KeyDef declares its own default value, so a settings UI can introspect the schema to generate widgets and the read path can fall back without re-declared defaults at call sites.
  • Backends are completely mockable. Store borrows an IBackend*, so tests construct a Store over their own in-memory IBackend without touching disk.

Dependencies

  • QtCore, QtGui. Zero Phosphor deps. This is a leaf library.