Phosphor
Qt6 / Wayland library suite for window-management tools
Loading...
Searching...
No Matches
Registry.h
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 fuddlesworth
2// SPDX-License-Identifier: LGPL-2.1-or-later
3#pragma once
4
7
8#include <QHash>
9#include <QList>
10#include <QMutex>
11#include <QString>
12#include <QtGlobal> // qWarning, qPrintable
13
14#include <memory>
15#include <type_traits>
16#include <utility> // std::move
17
18namespace PhosphorRegistry {
19
20// Generic, instance-per-composition-root registry of factories keyed by
21// their id() — the single id-keyed storage + change-notify primitive every
22// registry in the tree composes, so storage, lookup, ownership, threading,
23// and change signals are uniform instead of hand-rolled per registry.
24//
25// Used by the shell's five UI seams (bar widgets, control-center tiles,
26// launcher providers, OSDs, desktop widgets) AND by the domain registries
27// (shader packs, animation effects, tiling algorithms, layout sources,
28// easing curves). Entries are populated explicitly (UI built-ins, the curve
29// built-ins), by PluginLoader (.so packs), or by MetadataPackLoader<T>
30// (content packs scanned from disk).
31//
32// ## Thread safety
33//
34// Thread-safe: an internal QMutex guards the store, so registration,
35// unregistration, and lookup may run on any thread (e.g. a worker thread
36// loading a curve concurrently with a GUI-thread lookup) without corrupting
37// the store, and every read (factory/ids/forEach/size) returns a consistent
38// snapshot taken under the lock. The mutex is uncontended on the common
39// single-threaded GUI path, so the cost there is negligible. Change signals
40// are emitted via the RegistryNotifier AFTER the lock is released, so a slot
41// may safely call back into the registry; the notifier QObject keeps the
42// thread affinity of whoever created the Registry, and cross-thread emissions
43// reach consumers via queued connections.
44//
45// One caveat: the registration-ORDER guarantee on the change signals (below)
46// holds only for single-threaded mutation (the common GUI-thread case). Two
47// threads mutating concurrently each emit AFTER releasing the lock, so the
48// relative order of their signals is unspecified even though the store's
49// m_order — and therefore ids()/forEach() — stays correct. No signal is lost;
50// only cross-thread emission ordering is undefined.
51//
52// ## Duplicate id policy
53//
54// registerFactory rejects a duplicate id by default (first-registration
55// wins — the contract PluginLoader relies on for plugin id collisions).
56// Pass DuplicatePolicy::Replace to overwrite an existing entry instead
57// (the curve / algorithm registries replace a prior registration); a replace
58// fires factoryUnregistered(old) then factoryRegistered(new).
59//
60// ## Owner tags
61//
62// A factory may be registered under an owner tag so a subsystem that
63// contributes several factories can drop all of them in one call
64// (unregisterByOwner) — e.g. a plugin or a user-JSON loader retiring its
65// whole contribution. Untagged registrations (the empty tag) are the default
66// and are never matched by unregisterByOwner.
67//
68// A Replace adopts the NEW call's owner tag — it does not preserve the prior
69// entry's tag. A re-registration that wants to keep an entry in its owner
70// group must pass the same ownerTag again (a tag-less Replace moves the entry
71// to the untagged group). MetadataPackLoader and the algorithm registry
72// re-register untagged, so this is a no-op for them; CurveLoader, by contrast,
73// registers TAGGED (a per-loader owner tag) and deliberately re-passes that tag
74// on every Replace so its entries stay bulk-removable via unregisterByOwner in
75// ~CurveLoader.
76//
77// Header-only by design (no .cpp). The template body must be instantiable
78// from any consuming translation unit.
79
80// Behaviour when registerFactory hits an id that is already registered.
85
86template<typename Factory>
88{
89 static_assert(std::is_base_of_v<IFactoryBase, Factory>,
90 "Registry<T> requires T to derive from PhosphorRegistry::IFactoryBase");
91
92public:
93 Registry() = default;
94 ~Registry() = default;
95
96 Q_DISABLE_COPY_MOVE(Registry)
97
98 // Add @p factory under factory->id(). Returns true on success. A null
99 // factory or empty id is rejected (false + qWarning). A duplicate id is
100 // rejected by default (false + qWarning); pass DuplicatePolicy::Replace
101 // to overwrite it instead. @p ownerTag groups the entry for
102 // unregisterByOwner (empty = untagged, the default). The registry holds
103 // one shared_ptr ref; consumers can hold more via factory() / forEach().
104 bool registerFactory(std::shared_ptr<Factory> factory, const QString& ownerTag = QString(),
106 {
107 if (!factory) {
108 qWarning("PhosphorRegistry::Registry::registerFactory: null factory ignored");
109 return false;
110 }
111 const QString id = factory->id();
112 if (id.isEmpty()) {
113 qWarning("PhosphorRegistry::Registry::registerFactory: factory %p with empty id ignored",
114 static_cast<const void*>(factory.get()));
115 return false;
116 }
117 bool replaced = false;
118 {
119 QMutexLocker locker(&m_mutex);
120 if (m_entries.contains(id)) {
121 if (policy == DuplicatePolicy::Reject) {
122 qWarning("PhosphorRegistry::Registry::registerFactory: duplicate id '%s' ignored", qPrintable(id));
123 return false;
124 }
125 // Replace keeps the existing order position — a hot-reload that
126 // re-registers an id must not shuffle it to the end of the
127 // catalogue (the layout-source composite + algorithm UI lists
128 // rely on stable order across replacements).
129 replaced = true;
130 } else {
131 m_order.append(id);
132 }
133 m_entries.insert(id, Entry{std::move(factory), ownerTag});
134 }
135 // Signals fire outside the lock so a slot may re-enter the registry.
136 if (replaced) {
137 m_notifier.notifyUnregistered(id);
138 }
139 m_notifier.notifyRegistered(id);
140 return true;
141 }
142
143 // Remove the factory at @p id. Returns true if one was removed. No-op
144 // (returns false, no signal) if id is unknown. Existing shared_ptr refs
145 // held by consumers stay valid; the registry just drops its own ref.
146 bool unregisterFactory(const QString& id)
147 {
148 {
149 QMutexLocker locker(&m_mutex);
150 if (m_entries.remove(id) == 0) {
151 return false;
152 }
153 m_order.removeOne(id);
154 }
155 m_notifier.notifyUnregistered(id);
156 return true;
157 }
158
159 // Remove every factory registered under @p ownerTag. Returns the count
160 // removed. An empty tag matches nothing (untagged entries are never bulk-
161 // removable — that would wipe the whole registry by accident); returns 0.
162 int unregisterByOwner(const QString& ownerTag)
163 {
164 if (ownerTag.isEmpty()) {
165 qWarning("PhosphorRegistry::Registry::unregisterByOwner: empty owner tag matches nothing, ignored");
166 return 0;
167 }
168 QList<QString> removedIds;
169 {
170 QMutexLocker locker(&m_mutex);
171 // Walk m_order (not m_entries) so removedIds — and therefore the
172 // factoryUnregistered signals below — are in registration order,
173 // not QHash's hash order. Consumers rely on the ordered-signal
174 // contract (see signals_fireInRegistrationOrder).
175 for (const QString& id : std::as_const(m_order)) {
176 if (m_entries.value(id).ownerTag == ownerTag) {
177 removedIds.append(id);
178 }
179 }
180 for (const QString& id : std::as_const(removedIds)) {
181 m_entries.remove(id);
182 m_order.removeOne(id);
183 }
184 }
185 for (const QString& id : std::as_const(removedIds)) {
186 m_notifier.notifyUnregistered(id);
187 }
188 return static_cast<int>(removedIds.size());
189 }
190
191 // Drop every entry at once WITHOUT firing per-entry signals. For bulk
192 // teardown — a composition root shutting down, where consumers are tearing
193 // down too and per-entry unregister notifications are noise. A caller that
194 // needs to finalise object lifetimes (e.g. flush owned QObjects' deferred
195 // deletes) should snapshot the entries via forEach() BEFORE calling clear().
196 void clear()
197 {
198 QMutexLocker locker(&m_mutex);
199 m_entries.clear();
200 m_order.clear();
201 }
202
203 // Lookup. Returns the registered factory or a null shared_ptr if @p id is
204 // unknown. The returned shared_ptr keeps the factory alive even if it is
205 // unregistered concurrently.
206 [[nodiscard]] std::shared_ptr<Factory> factory(const QString& id) const
207 {
208 QMutexLocker locker(&m_mutex);
209 const auto it = m_entries.constFind(id);
210 return it == m_entries.cend() ? std::shared_ptr<Factory>() : it.value().factory;
211 }
212
213 // Snapshot of currently-registered ids in REGISTRATION (insertion) order:
214 // the order registerFactory was first called for each id, with a Replace
215 // keeping the original position and an unregister removing it. Deterministic
216 // and stable — consumers that need a different display order (e.g.
217 // alphabetical) sort the result themselves; consumers that need the
218 // composition / priority order (the layout-source composite, algorithm UI
219 // lists) get it for free.
220 [[nodiscard]] QList<QString> ids() const
221 {
222 QMutexLocker locker(&m_mutex);
223 return m_order;
224 }
225
226 // Functional iteration over a SNAPSHOT taken under the lock, in
227 // registration (insertion) order: the visitor is called as
228 // `visitor(const std::shared_ptr<Factory>&)` for each factory, outside the
229 // lock. Mutating the registry from the visitor is therefore safe (it
230 // affects the next iteration, not this snapshot).
231 template<typename Visitor>
232 void forEach(Visitor&& visitor) const
233 {
234 QList<std::shared_ptr<Factory>> snapshot;
235 {
236 QMutexLocker locker(&m_mutex);
237 snapshot.reserve(m_order.size());
238 for (const QString& id : m_order) {
239 const auto it = m_entries.constFind(id);
240 if (it != m_entries.cend()) {
241 snapshot.append(it.value().factory);
242 }
243 }
244 }
245 for (const std::shared_ptr<Factory>& factory : std::as_const(snapshot)) {
246 visitor(factory);
247 }
248 }
249
250 // Access the signal carrier. Survives for the registry's lifetime;
251 // consumers connect during composition-root setup and rely on Qt's
252 // connection auto-disconnect when either end is destroyed.
253 [[nodiscard]] RegistryNotifier* notifier()
254 {
255 return &m_notifier;
256 }
257 [[nodiscard]] const RegistryNotifier* notifier() const
258 {
259 return &m_notifier;
260 }
261
262 // True if no factories are currently registered.
263 [[nodiscard]] bool isEmpty() const
264 {
265 QMutexLocker locker(&m_mutex);
266 return m_entries.isEmpty();
267 }
268
269 // Number of currently-registered factories.
270 [[nodiscard]] qsizetype size() const
271 {
272 QMutexLocker locker(&m_mutex);
273 return m_entries.size();
274 }
275
276private:
277 struct Entry
278 {
279 std::shared_ptr<Factory> factory;
280 QString ownerTag;
281 };
282
283 mutable QMutex m_mutex;
284 QHash<QString, Entry> m_entries;
285 // Registration (insertion) order of the ids in m_entries — appended on a
286 // fresh register, position-preserved on a Replace, removed on unregister.
287 // Backs ids() / forEach() so iteration is deterministic and stable rather
288 // than QHash's hash order. Kept in lockstep with m_entries under m_mutex.
289 QList<QString> m_order;
290 // Owned by value; default-constructed parentless. notifier() hands out a
291 // pointer so consumers can connect, but ownership stays inside the
292 // Registry. Signals are emitted outside m_mutex (see registerFactory).
293 RegistryNotifier m_notifier;
294};
295
296} // namespace PhosphorRegistry
Definition RegistryNotifier.h:32
qsizetype size() const
Definition Registry.h:270
bool unregisterFactory(const QString &id)
Definition Registry.h:146
bool registerFactory(std::shared_ptr< Factory > factory, const QString &ownerTag=QString(), DuplicatePolicy policy=DuplicatePolicy::Reject)
Definition Registry.h:104
bool isEmpty() const
Definition Registry.h:263
QList< QString > ids() const
Definition Registry.h:220
void clear()
Definition Registry.h:196
const RegistryNotifier * notifier() const
Definition Registry.h:257
void forEach(Visitor &&visitor) const
Definition Registry.h:232
std::shared_ptr< Factory > factory(const QString &id) const
Definition Registry.h:206
RegistryNotifier * notifier()
Definition Registry.h:253
int unregisterByOwner(const QString &ownerTag)
Definition Registry.h:162
Definition IBarWidgetFactory.h:16
DuplicatePolicy
Definition Registry.h:81
@ Replace
Overwrite; fire factoryUnregistered(old) + factoryRegistered(new).
Definition Registry.h:83
@ Reject
Keep the existing entry, log + return false (default).
Definition Registry.h:82