Typed JSON-over-Unix-socket invocation channel for Phosphor applications such as phosphor-shell. Lets compositor keybinds, external scripts, and other shells drive Phosphor actions by verb (phosphorctl call launcher.toggle) without rebuilding the existing D-Bus surface.
Modern Wayland shells (DMS, Noctalia, Quickshell) all ship a typed CLI built on a single socket, with JSON-shaped requests and schema-described targets. phosphor-ipc is Phosphor's equivalent. It sits alongside the existing D-Bus adaptors. Service libraries register both an IPC target and (where appropriate) a D-Bus method for each callable.
The library owns:
Ships alongside the phosphorctl CLI at phosphor-shell/cli/phosphorctl/, which provides call, list, schema, and subscribe subcommands.
| Type | Purpose |
|---|---|
| PhosphorIpc::IpcRouter | Per-application dispatcher. Owns one QLocalServer, the registry of named targets, and the per-socket subscription set. Single-threaded: the thread that owns it, normally the GUI thread. |
| PhosphorIpc::IpcTarget | QML element. Each instance binds to one target name. Functions declared on the instance become callable, and the explicit emitEvent(name, args) pushes wire events. |
| PhosphorIpc::IpcProtocol | Wire-format constants + parser/serialiser. Shared between the library (server) and the phosphorctl binary (client). |
| PhosphorIpc::IpcEngine | Bridge between an application-owned IpcRouter and QML-side IpcTarget instances. |
| PhosphorIpc::IpcSchemaGenerator | QMetaObject → JSON Schema. Used by the schema response and by the CLI for client-side argument validation. |
| PhosphorIpc::IpcCallContext | Mixin for a C++ target. sendErrorReply(message) fails the running wire call with CALL_FAILED, like QDBusContext does for D-Bus. deferReply() defers the answer to an IpcPendingReply, connectionId() names the client connection that made the call, and connectionPid() the process that opened it. |
| PhosphorIpc::IpcPendingReply | Move-only handle to a deferred call. finish(result) or fail(...) answers it once, and dropping it unanswered fails it with CALL_ABANDONED. |
One JSON object per line, \n-terminated, UTF-8. Same NDJSON shape as niri-ipc and hyprland-ipc. Stable across protocol version 1. The version is a build-time invariant only (the PHOSPHOR_IPC_PROTOCOL_VERSION compile definition is cross-checked by a static_assert in IpcProtocol.h). It is NOT transmitted on the wire and there is currently no version-negotiation handshake. Incompatible bumps surface as malformed-request errors against an older peer.
// Call
{"type":"call","id":42,"target":"greet","fn":"sayHello","args":["nate"]}
// Enumerate targets
{"type":"list","id":43}
// Schema for one target
{"type":"schema","id":44,"target":"greet"}
// Subscribe to a signal. Server streams events tagged with this id
// until unsubscribe / disconnect
{"type":"subscribe","id":45,"target":"count","signal":"countChanged"}
// Cancel a subscription
{"type":"unsubscribe","id":46,"subscriptionId":45}
{"type":"reply","id":42,"result":"Hello, nate"}
// Event to a subscription
{"type":"event","subscriptionId":45,"args":[7]}
// Event to one connection (IpcRouter::sendEvent), with no subscription
{"type":"event","target":"pkg","signal":"output","args":["fetching"]}
{"type":"error","id":42,"code":"NO_SUCH_TARGET","message":"...","detail":{}}Error codes: NO_SUCH_TARGET, NO_SUCH_FN, NO_SUCH_SIGNAL, NO_SUCH_SUBSCRIPTION, INVALID_ARG, INVOCATION_FAILED, MALFORMED_REQUEST, CALL_FAILED, CALL_ABANDONED. A deferred reply may also fail with a code of the target's own.
INVOCATION_FAILED means that the router could not run the method. CALL_FAILED means that the method ran and failed the call itself (see Failing a call). CALL_ABANDONED means that the target deferred the reply and then dropped the call without answering it (see Answering later).
Every reply and request-correlated error carries the request's id, and the client matches them by it. Most calls are answered in request order, but a deferred call is answered when the target finishes it, which may be after the replies to calls made later on the same connection. A client that keeps more than one request in flight gives each its own id, one that no live subscription on the connection uses either: the error that ends a subscription carries the subscription id. Everything the router writes to one connection arrives in the order it was written.
#include <PhosphorIpc/IpcEngine.h>
#include <PhosphorIpc/IpcRouter.h>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char** argv) {
QGuiApplication app(argc, argv);
// Declare `router` BEFORE `engine` so reverse-order destruction
// tears the engine down FIRST; otherwise QML-side IpcTarget
// instances would unregister against a dead router.
PhosphorIpc::IpcRouter router;
if (!router.start()) { // binds $XDG_RUNTIME_DIR/phosphor.sock
qWarning("IPC router failed to start "
"(XDG_RUNTIME_DIR unset, another live listener on "
"the same path, or insufficient permissions)");
// Application can continue without IPC; failure is non-fatal.
// The router auto-recovers from STALE socket files (left
// behind by a crashed previous run) — those don't cause
// start() failures.
}
QQmlApplicationEngine engine;
PhosphorIpc::IpcEngine::install(&engine, &router);
engine.loadFromModule(...); // shell QML
return app.exec();
}The shell QML can now declare IpcTarget instances anywhere in the component tree, and each one auto-registers via the router stashed on the engine.
import Phosphor.Ipc
import Phosphor.Theme // for Theme singleton; omit if not needed
IpcTarget {
target: "theme"
signal modeChanged(string mode) // schema-visible
function setMode(mode: string) {
Theme.mode = mode // apply state mutation
modeChanged(mode) // notify in-QML observers
emitEvent("modeChanged", [mode]) // broadcast on the WIRE
}
}The schema generator surfaces both Q_INVOKABLE methods and declared signals, so phosphorctl schema theme shows the subscribable surface.
Calling the QML signal (e.g. modeChanged(mode)) does NOT broadcast to wire subscribers. It only fires in-QML connections. Wire delivery happens through emitEvent(name, args) exclusively. The split is by design. Introspecting Qt signals via qt_metacall collides with moc-generated dispatch, and explicit emitEvent matches the "wire-visible state transitions are an explicit contract" model. Plugin authors must call both for in-QML AND wire delivery.
A method that cannot do what the client asked fails the call, so that the client gets an error frame instead of a reply:
{"type":"error","id":42,"code":"CALL_FAILED","message":"no pane 7","detail":{}}A C++ target inherits IpcCallContext next to QObject and calls sendErrorReply while its method runs:
class Control : public QObject, protected PhosphorIpc::IpcCallContext
{
Q_OBJECT
public:
Q_INVOKABLE int focus(int pane)
{
if (!exists(pane)) {
sendErrorReply(QStringLiteral("no pane %1").arg(pane));
return 0; // dropped
}
...
}
};A QML function calls sendErrorReply on its IpcTarget:
IpcTarget {
target: "theme"
function setMode(mode: string) {
if (mode !== "light" && mode !== "dark") {
sendErrorReply("mode is light or dark")
return
}
Theme.mode = mode
}
}The return value of a failed call is dropped. Outside a wire call (a direct C++ call, a QML binding) calledFromIpc() is false and sendErrorReply does nothing. The same goes for the target's other slots that a nested event loop inside the method runs (QEventLoop::exec, QDialog::exec), where sendErrorReply and deferReply also warn that they did nothing. QCoreApplication::processEvents does not start a loop of its own, and the slots it runs see the method's call. Either way a method that waits for something defers its reply instead of waiting in a loop. A nested loop also holds back the later requests of the method's own connection until the method returns, so a method must never wait there for another request from the same client. IpcRouter::invoke reports the failure as InvokeOutcome::CallFailed with the target's message.
A call that takes a while (it runs a process, waits for the user) need not block the router. The method defers its reply and returns at once, and the target answers through the IpcPendingReply it keeps:
class Packages : public QObject, protected PhosphorIpc::IpcCallContext
{
Q_OBJECT
public:
explicit Packages(PhosphorIpc::IpcRouter& router);
Q_INVOKABLE void install(const QString& name)
{
Job& job = newJob();
job.reply = deferReply(); // no reply goes out on return
startJob(job, name); // may end at once, and answer
}
Q_SIGNALS:
void output(const QString& line); // listed by the schema
private:
void onOutput(Job& job, const QString& line)
{
// To the caller only, ahead of the reply.
m_router.sendEvent(job.reply.connectionId(), QStringLiteral("pkg"), QStringLiteral("output"), {line});
}
void onFinished(Job& job, int exitCode)
{
if (exitCode == 0) {
job.reply.finish(QJsonValue::Null);
} else {
job.reply.fail(QStringLiteral("exit code %1").arg(exitCode));
}
}
...
};Defer before the work starts, so that work that ends at once can answer, and keep one pending reply per call: a single member that every call assigns to abandons the call it held when the next one comes. The router sends no reply when a deferring method returns, and drops its return value. Calls on the same connection go on being answered meanwhile. The rules:
QML functions have no deferReply. A deferred call needs a C++ target.
The router gives every client connection it accepts an id, unique in the process and never reused, also across routers. While a call runs, IpcCallContext::connectionId() returns the id of the connection that made it, and 0 for a call that came from no connection (a direct IpcRouter::invoke) or outside a call.
IpcCallContext::connectionPid() returns the process ID of the client that made the call. The router reads it from the kernel (SO_PEERCRED) once, when it accepts the connection, so it names the process that connected and a client cannot claim another. It is 0 where connectionId() is 0, and on a platform other than Linux or when the kernel gives no answer.
IpcRouter::sendEvent(connectionId, target, signal, args) writes one event to that connection, whether it subscribed to anything or not. It is meant for a call's own output, sent to the client that made the call. The frame names the event with target and signal and carries no subscriptionId. Declare the event as a signal on the target, as for broadcast events, so phosphorctl schema lists it. The schema then also offers the signal for subscription, and a subscriber gets only what broadcastEvent sends under that name: a target that wants both kinds of listener calls both. The id belongs to the router that runs the call, so a target registered on several routers sends through the one that accepted the connection. sendEvent returns true when the event was queued on an open connection. It returns false, and writes nothing, for an empty target or signal name, for an id that names no open connection of the router, and off the router's thread (an assert in debug builds, a warning in release builds; broadcastEvent drops its event the same way). The output limit of broadcasts applies: a connection more than 16 MiB behind is closed with a warning, and sendEvent returns false. A fifth argument, qint64* lineBytes, receives the size of the line that the event took, its newline included, for a target that counts the bytes its client has read. It is 0 when sendEvent returns false.
IpcRouter::connectionClosed(id) follows the close of every connection, once: the client went away, the router closed it, or stop() ran. It is sent from the event loop, never synchronously from inside a call into the router such as sendEvent or stop, so a slot can stop that connection's work and destroy its pending replies on the spot. A target method that spins a nested event loop can get it inside that loop, as it can any queued signal. The router's destructor sends it for the connections it closes. A receiver that holds the router as a member is partly destroyed by then, so it declares the router after the state its slot uses, or disconnects first. A client that gets an event it did not subscribe to is free to skip it. phosphorctl call prints the events sent to its call on stderr, and phosphorctl subscribe prints every event it receives.
IpcRouter::connectionOpened(id) comes when the router accepts a connection, before it reads anything from it, and connectionCount() returns the connections open now. setMaxConnections(max) caps them, for a socket that other processes can reach, such as one forwarded to another host. A connection accepted while max are open is closed at once and unread. It gets no id, connectionOpened and connectionClosed do not come for it, and connectionRefused() does. Lowering the cap closes no open connection. The default, 0, sets no limit.
stop() closes each connection at once and drops what is still unwritten to it, so answers written just before it never arrive. stop(IpcRouter::StopMode::Flush) delivers them first: the router stops listening and forgets its connections at once, as stop() does, and each connection closes when the client has taken what was written to it. A client that does not read within the timeout (DefaultFlushTimeoutMs, 5 seconds, or the second argument) loses the rest. The delivery does not need the router, which may be destroyed right after the call.
phosphorctl call theme.setMode --arg mode=dark
phosphorctl call pkg.install --arg name=foo --timeout 0 # waits for a deferred answer
phosphorctl list
phosphorctl schema theme | jq
phosphorctl subscribe theme.modeChanged # stays connected, streams eventsSocket-path priority: --socket PATH > $PHOSPHOR_SOCKET > $XDG_RUNTIME_DIR/phosphor.sock.
phosphorctl call waits two seconds for the answer by default. --timeout SECONDS changes that, and --timeout 0 waits without a limit, for a deferred call that answers when its work ends. Events the target sends to the call go to stderr as they arrive, one compact JSON line each, so stdout carries only the result.
phosphor-shell-libs/examples/phosphor-ipc-demo/ is the canonical end-to-end exercise. The demo window includes a live event-log panel that mirrors the broadcast stream. Running phosphorctl call count.increment from a single sidecar terminal makes events appear in the demo window in real time, with no separate phosphorctl subscribe terminal needed:
# terminal 1
./bin/phosphor-ipc-demo --socket /tmp/p.sock
# terminal 2
export PHOSPHOR_SOCKET=/tmp/p.sock
phosphorctl call count.increment # demo's event log gains an entry
phosphorctl subscribe count.countChanged # optional: same events on stdout