Phosphor
Qt6 / Wayland library suite for window-management tools
Loading...
Searching...
No Matches
PerScreenStates.h
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 fuddlesworth
2// SPDX-License-Identifier: LGPL-2.1-or-later
3
4#pragma once
5
6#include "phosphorengine_export.h"
7
10
11#include <functional>
12#include <optional>
13#include <type_traits>
14
15#include <QHash>
16#include <QList>
17#include <QLoggingCategory>
18#include <QString>
19#include <QStringList>
20#include <QtGlobal>
21
22namespace PhosphorEngine {
23
26Q_DECLARE_EXPORTED_LOGGING_CATEGORY(lcPerScreenStates, PHOSPHORENGINE_EXPORT)
27
28
43template<typename StateT>
45{
46 static_assert(std::is_base_of_v<IPlacementState, StateT>,
47 "PerScreenStates<StateT>: StateT must implement PhosphorEngine::IPlacementState");
48
49public:
53 StateT* forKey(const PlacementStateKey& key, const std::function<StateT*()>& factory)
54 {
55 auto it = m_states.find(key);
56 if (it != m_states.end()) {
57 return it.value();
58 }
59 StateT* created = factory ? factory() : nullptr;
60 if (created) {
61 m_states.insert(key, created);
62 }
63 return created;
64 }
65
67 StateT* stateForKey(const PlacementStateKey& key) const
68 {
69 return m_states.value(key);
70 }
71
72 bool containsKey(const PlacementStateKey& key) const
73 {
74 return m_states.contains(key);
75 }
76
78 void insertState(const PlacementStateKey& key, StateT* state)
79 {
80 m_states.insert(key, state);
81 }
82
84 StateT* takeState(const PlacementStateKey& key)
85 {
86 return m_states.take(key);
87 }
88
89 int stateCount() const
90 {
91 return m_states.size();
92 }
93
95 const QHash<PlacementStateKey, StateT*>& states() const
96 {
97 return m_states;
98 }
99
100 // ── Reverse (window -> memberships) map ──────────────────────────────────
101 //
102 // A window is a member of every state that holds it. Almost always that is
103 // exactly one, and for those the accessors below answer precisely what the
104 // single-key map they replaced answered. More than one arises when a window
105 // is present on several desktops at once — sticky (on all of them), or a
106 // span like {1,2} — and the engines give it a place in each, so it can be
107 // tiled or snapped differently per desktop instead of existing in whichever
108 // context happened to be current when it opened.
109
115 using ContextKeyResolver = std::function<PlacementStateKey(const QString& screenId)>;
116
118 {
119 m_contextKeyResolver = std::move(resolver);
120 }
121
122 bool hasWindow(const QString& windowId) const
123 {
124 return m_windowMemberships.contains(windowId);
125 }
126
129 PlacementStateKey keyForWindow(const QString& windowId) const
130 {
131 return primaryOf(m_windowMemberships.value(windowId));
132 }
133
135 std::optional<PlacementStateKey> windowKey(const QString& windowId) const
136 {
137 auto it = m_windowMemberships.constFind(windowId);
138 if (it == m_windowMemberships.constEnd()) {
139 return std::nullopt;
140 }
141 return primaryOf(it.value());
142 }
143
145 QList<PlacementStateKey> membershipsForWindow(const QString& windowId) const
146 {
147 return m_windowMemberships.value(windowId);
148 }
149
154 bool hasMembership(const QString& windowId, const PlacementStateKey& key) const
155 {
156 return m_windowMemberships.value(windowId).contains(key);
157 }
158
163 void setKeyForWindow(const QString& windowId, const PlacementStateKey& key)
164 {
165 m_windowMemberships.insert(windowId, {key});
166 }
167
170 void addMembership(const QString& windowId, const PlacementStateKey& key)
171 {
172 QList<PlacementStateKey>& keys = m_windowMemberships[windowId];
173 if (!keys.contains(key)) {
174 keys.append(key);
175 }
176 }
177
181 void removeMembership(const QString& windowId, const PlacementStateKey& key)
182 {
183 auto it = m_windowMemberships.find(windowId);
184 if (it == m_windowMemberships.end()) {
185 return;
186 }
187 it.value().removeAll(key);
188 if (it.value().isEmpty()) {
189 m_windowMemberships.erase(it);
190 }
191 }
192
194 void removeWindow(const QString& windowId)
195 {
196 m_windowMemberships.remove(windowId);
197 }
198
201 PlacementStateKey takeWindow(const QString& windowId)
202 {
203 return primaryOf(m_windowMemberships.take(windowId));
204 }
205
207 QStringList trackedWindowIds() const
208 {
209 return m_windowMemberships.keys();
210 }
211
214 void forEachMembership(const std::function<void(const QString&, const PlacementStateKey&)>& fn) const
215 {
216 if (!fn) {
217 return;
218 }
219 for (auto it = m_windowMemberships.cbegin(); it != m_windowMemberships.cend(); ++it) {
220 for (const PlacementStateKey& key : it.value()) {
221 fn(it.key(), key);
222 }
223 }
224 }
225
230 StateT* forWindow(const QString& windowId, PlacementStateKey* outKey = nullptr) const
231 {
232 auto it = m_windowMemberships.constFind(windowId);
233 if (it == m_windowMemberships.constEnd()) {
234 return nullptr;
235 }
236 const PlacementStateKey key = primaryOf(it.value());
237 if (outKey) {
238 *outKey = key;
239 }
240 return m_states.value(key);
241 }
242
248 void migrate(const QString& windowId, const PlacementStateKey& oldKey, const PlacementStateKey& newKey)
249 {
250 // A move onto itself is a no-op, not a merge: the merge arm below
251 // would find newKey already held and remove the entry at `at`, which
252 // for a single-membership window is its only one.
253 if (oldKey == newKey) {
254 return;
255 }
256 // Debug assert AND a release-build warning for the same condition: a
257 // stale-caller bug silently rewrote the reverse map in release, which
258 // is exactly the case that leaves a window resolving to a state that
259 // does not hold it. The move still happens either way — the map is
260 // authoritative and refusing here would strand the window worse — so
261 // this reports rather than guards.
262 auto it = m_windowMemberships.find(windowId);
263 if (it != m_windowMemberships.end() && !it.value().contains(oldKey)) {
264 Q_ASSERT(false);
265 qCWarning(lcPerScreenStates) << "PerScreenStates::migrate: caller asserted" << windowId << "was on desktop"
266 << oldKey.desktop << "of screen" << oldKey.screenId
267 << "but its memberships are" << it.value().size() << "key(s) not including"
268 << "that one — migrating the primary instead";
269 }
270 if (it == m_windowMemberships.end()) {
271 m_windowMemberships.insert(windowId, {newKey});
272 return;
273 }
274 // Move the asserted membership, leaving the window's OTHER contexts
275 // alone: a multi-desktop window migrating on one desktop keeps its
276 // place on the rest. Falls back to the primary when the asserted key
277 // is not held, which is the stale-caller case warned about above.
278 QList<PlacementStateKey>& keys = it.value();
279 const qsizetype at = keys.indexOf(keys.contains(oldKey) ? oldKey : primaryOf(keys));
280 if (at < 0) {
281 keys.append(newKey);
282 return;
283 }
284 if (keys.contains(newKey)) {
285 keys.removeAt(at); // already a member there; the move is a merge
286 } else {
287 keys[at] = newKey;
288 }
289 }
290
293 void rekeyWindows(const PlacementStateKey& oldKey, const PlacementStateKey& newKey)
294 {
295 for (auto it = m_windowMemberships.begin(); it != m_windowMemberships.end(); ++it) {
296 QList<PlacementStateKey>& keys = it.value();
297 const qsizetype at = keys.indexOf(oldKey);
298 if (at < 0) {
299 continue;
300 }
301 if (keys.contains(newKey)) {
302 keys.removeAt(at);
303 } else {
304 keys[at] = newKey;
305 }
306 }
307 }
308
314 void removeStatesIf(const std::function<bool(const PlacementStateKey&, StateT*)>& pred,
315 const std::function<void(const PlacementStateKey&, StateT*)>& onRemove)
316 {
317 for (auto it = m_states.begin(); it != m_states.end();) {
318 if (pred(it.key(), it.value())) {
319 if (onRemove) {
320 onRemove(it.key(), it.value());
321 }
322 it = m_states.erase(it);
323 } else {
324 ++it;
325 }
326 }
327 }
328
333 void removeWindowsIf(const std::function<bool(const QString&, const PlacementStateKey&)>& pred)
334 {
335 if (!pred) {
336 return;
337 }
338 for (auto it = m_windowMemberships.begin(); it != m_windowMemberships.end();) {
339 QList<PlacementStateKey>& keys = it.value();
340 const QString& windowId = it.key();
341 keys.removeIf([&pred, &windowId](const PlacementStateKey& key) {
342 return pred(windowId, key);
343 });
344 if (keys.isEmpty()) {
345 it = m_windowMemberships.erase(it);
346 } else {
347 ++it;
348 }
349 }
350 }
351
352private:
356 PlacementStateKey primaryOf(const QList<PlacementStateKey>& keys) const
357 {
358 if (keys.isEmpty()) {
359 return {};
360 }
361 if (keys.size() == 1 || !m_contextKeyResolver) {
362 return keys.first();
363 }
364 for (const PlacementStateKey& key : keys) {
365 if (m_contextKeyResolver(key.screenId) == key) {
366 return key;
367 }
368 }
369 // Every membership is off-context (the window is on desktops the user
370 // is not looking at on any of its screens). Any of them beats none:
371 // the callers that land here are asking "where is this window tracked",
372 // and a null answer reads as untracked, which it is not.
373 return keys.first();
374 }
375
376 QHash<PlacementStateKey, StateT*> m_states;
377 QHash<QString, QList<PlacementStateKey>> m_windowMemberships;
378 ContextKeyResolver m_contextKeyResolver;
379};
380
381} // namespace PhosphorEngine
Exported because this is a header-only template used from every engine library, so the category has t...
Definition PerScreenStates.h:45
bool containsKey(const PlacementStateKey &key) const
Definition PerScreenStates.h:72
bool hasWindow(const QString &windowId) const
Definition PerScreenStates.h:122
StateT * takeState(const PlacementStateKey &key)
Remove and return the state at key (nullptr if absent). Does not delete.
Definition PerScreenStates.h:84
PlacementStateKey keyForWindow(const QString &windowId) const
The PRIMARY key for windowId, or a default-constructed key when untracked (an empty screenId marks "n...
Definition PerScreenStates.h:129
StateT * stateForKey(const PlacementStateKey &key) const
The state for key, or nullptr if none exists (never creates).
Definition PerScreenStates.h:67
void migrate(const QString &windowId, const PlacementStateKey &oldKey, const PlacementStateKey &newKey)
Move a window's reverse-map entry from oldKey to newKey.
Definition PerScreenStates.h:248
StateT * forKey(const PlacementStateKey &key, const std::function< StateT *()> &factory)
Lazily creates the state for key if absent.
Definition PerScreenStates.h:53
std::function< PlacementStateKey(const QString &screenId)> ContextKeyResolver
Resolves the key a screen is CURRENTLY showing.
Definition PerScreenStates.h:115
void removeWindow(const QString &windowId)
Drop EVERY membership for windowId (does not touch state objects).
Definition PerScreenStates.h:194
void removeStatesIf(const std::function< bool(const PlacementStateKey &, StateT *)> &pred, const std::function< void(const PlacementStateKey &, StateT *)> &onRemove)
Lockstep prune of the forward map: for every state matching pred, invoke onRemove (engine-specific te...
Definition PerScreenStates.h:314
StateT * forWindow(const QString &windowId, PlacementStateKey *outKey=nullptr) const
Resolve the state holding windowId's PRIMARY membership (no create).
Definition PerScreenStates.h:230
void insertState(const PlacementStateKey &key, StateT *state)
Insert/replace the state at key (caller retains ownership semantics).
Definition PerScreenStates.h:78
void setKeyForWindow(const QString &windowId, const PlacementStateKey &key)
Make key the window's ONLY membership.
Definition PerScreenStates.h:163
void rekeyWindows(const PlacementStateKey &oldKey, const PlacementStateKey &newKey)
Rewrite every membership equal to oldKey to newKey.
Definition PerScreenStates.h:293
int stateCount() const
Definition PerScreenStates.h:89
void addMembership(const QString &windowId, const PlacementStateKey &key)
Add key to the window's memberships, keeping the ones it has.
Definition PerScreenStates.h:170
bool hasMembership(const QString &windowId, const PlacementStateKey &key) const
Whether windowId belongs to the state at key specifically.
Definition PerScreenStates.h:154
void removeWindowsIf(const std::function< bool(const QString &, const PlacementStateKey &)> &pred)
Drop MEMBERSHIPS matching pred (e.g.
Definition PerScreenStates.h:333
void removeMembership(const QString &windowId, const PlacementStateKey &key)
Drop one membership.
Definition PerScreenStates.h:181
PlacementStateKey takeWindow(const QString &windowId)
Remove every membership and return the primary (default key when absent), mirroring QHash::take.
Definition PerScreenStates.h:201
QStringList trackedWindowIds() const
Every tracked window id, once each however many states hold it.
Definition PerScreenStates.h:207
QList< PlacementStateKey > membershipsForWindow(const QString &windowId) const
Every state this window belongs to, in the order they were added.
Definition PerScreenStates.h:145
void setContextKeyResolver(ContextKeyResolver resolver)
Definition PerScreenStates.h:117
void forEachMembership(const std::function< void(const QString &, const PlacementStateKey &)> &fn) const
Visit every (windowId, key) membership pair.
Definition PerScreenStates.h:214
const QHash< PlacementStateKey, StateT * > & states() const
Read-only view of the forward map for iteration.
Definition PerScreenStates.h:95
std::optional< PlacementStateKey > windowKey(const QString &windowId) const
The PRIMARY key for windowId, or nullopt when untracked.
Definition PerScreenStates.h:135
Definition DesktopRemap.h:12
Identity of a per-screen placement state: a window's placement is scoped to the (screen,...
Definition EngineTypes.h:25
int desktop
Definition EngineTypes.h:27
QString screenId
Definition EngineTypes.h:26