Phosphor
Qt6 / Wayland library suite for window-management tools
Loading...
Searching...
No Matches
WorkspaceReconciler.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
7#include "phosphorworkspaces_export.h"
8
9#include <functional>
10
11#include <QElapsedTimer>
12#include <QHash>
13#include <QList>
14#include <QObject>
15#include <QSet>
16#include <QString>
17#include <QStringList>
18#include <QTimer>
19
20namespace PhosphorWorkspaces {
21
23struct PHOSPHORWORKSPACES_EXPORT NamedWorkspace
24{
30 QString id;
31 QString name;
32 QString outputId;
35 int position = -1;
36};
37
64class PHOSPHORWORKSPACES_EXPORT WorkspaceReconciler : public QObject
65{
66 Q_OBJECT
67
68public:
69 explicit WorkspaceReconciler(QObject* parent = nullptr);
70
71 static constexpr int LedgerTimeoutMs = 2000;
72 static constexpr int DestroyDebounceMs = 300;
79 static constexpr int MaxRemovalRefusals = 3;
90 static constexpr int MaxCreateRefusals = 3;
96 static constexpr int MaxSetCurrentRefusals = 3;
104 static constexpr int DefaultDesktopCap = 25;
110 static constexpr int CapProbeExpiries = 2;
115 static_assert(CapProbeExpiries <= MaxCreateRefusals, "the cap probe needs a re-drive between its expiries");
122 static constexpr int MaxNamePushRefusals = 3;
123
124 const WorkspaceMap& map() const;
125 quint64 generation() const;
126
133 bool restoreState(const QString& json, const std::function<QString(const QString&)>& canonicalScreenId = {});
136 bool isAdopted() const;
137
139 int desktopCap() const;
144 void setDesktopCap(int cap);
149 int ledgerTimeoutMs() const;
150 int destroyDebounceMs() const;
154 void setFocusedScreen(const QString& screenId);
159 void setFocusedScreenProvider(std::function<QString()> provider);
165 void setDefaultDesktopNameProvider(std::function<QString(int)> provider);
166
167 // ── Inputs (notifications; plain calls) ─────────────────────────────────
175 void onDesktopListSettled(const QStringList& ids, const QStringList& rawNames = {});
178 void onKwinDesktopCreated(const QString& desktopId);
184 void onKwinDesktopCreatedAt(const QString& desktopId, int position, const QString& name);
186 void onKwinDesktopRemoved(const QString& desktopId);
195 void onCreateDesktopAnswered(uint position, const QString& name, bool answered);
199 void onRemoveDesktopAnswered(const QString& desktopId, bool answered);
205 void onKwinDesktopRenamed(const QString& desktopId, const QString& rawName);
221 bool onScreenDesktopReport(const QString& screenId, int desktop);
227 void onScreenDesktopSeeded(const QString& screenId, int desktop);
229 void onPopulationChanged(const QString& desktopId, int windowCount);
230 void onScreenAdded(const QString& screenId);
231 void onScreenRemoved(const QString& screenId);
237 void onScreenRenamed(const QString& fromScreenId, const QString& toScreenId);
239 void onScreenOrderChanged(const QStringList& order);
240
260 bool adoptAll(const QStringList& ids, const QHash<QString, QString>& currentDesktopIdByScreen,
261 const QHash<QString, QString>& preferredScreenByDesktopId = {}, const QStringList& rawNames = {});
262
281 void applyNamedWorkspaces(const QList<NamedWorkspace>& declarations, const QStringList& kwinNames);
282
283 // ── Verb support ────────────────────────────────────────────────────────
291 QString currentDesktopIdOf(const QString& screenId) const;
295 QHash<QString, int> currentIndexByScreen() const;
299 QString desktopIdAtOffset(const QString& screenId, int delta) const;
303 QString desktopIdAtOffsetFrom(const QString& screenId, const QString& fromDesktopId, int delta) const;
305 QString desktopIdAtSliceIndex(const QString& screenId, int sliceIndex) const;
307 QString inFlightSetCurrentTarget(const QString& screenId) const;
308
314 bool issueSetCurrent(const QString& screenId, const QString& desktopId);
320 bool issueSetCurrentReplacing(const QString& screenId, const QString& desktopId);
324 bool snapBack(const QString& screenId);
328 bool reorderCurrentWorkspace(const QString& screenId, int delta);
335 QString transferCurrentWorkspace(const QString& screenId, const QString& targetScreenId);
336
337Q_SIGNALS:
338 // Outputs → KWin (via VirtualDesktopManager). Creates, removes and
339 // switches are ledgered before the emit; name pushes are not.
343 void requestCreateDesktop(uint position, const QString& name);
344 void requestRemoveDesktop(const QString& desktopId);
345 void requestSetCurrent(const QString& screenId, const QString& desktopId);
349 void requestSetDesktopName(const QString& desktopId, const QString& name);
350
362 void foreignSwitchDetected(const QString& screenId, const QString& desktopId, const QString& ownerScreenId);
368 void removalRaceDetected(const QString& desktopId, const QString& ownerScreenId);
372 void removalAbandoned(const QString& desktopId);
377 void namedWorkspaceMoved(const QString& namedId, const QString& name, const QString& screenId, int sliceIndex);
384 void namedWorkspaceRenamedInKWin(const QString& namedId, const QString& desktopId, const QString& kwinName);
389
390private:
391 struct PendingOp
392 {
393 enum class Kind {
394 Create,
395 Remove,
396 SetCurrent
397 };
398 Kind kind;
401 QString desktopId;
402 QString screenId;
408 int declaredPosition = -1;
412 int globalPosition = 0;
413 QString name;
416 QString kwinName;
417 QString namedId;
418 qint64 deadline = 0;
421 bool echoed = false;
424 bool replaceable = false;
429 int supersededAnswers = 0;
431 bool replied = false;
434 bool stalled = false;
435 };
436
437 qint64 nowMs() const;
443 QString recordScreenDesktop(const QString& screenId, int desktop, bool restoresCorrectionBudget = true);
447 int openSetCurrentIndex(const QString& screenId) const;
449 int matchAnsweredOp(PendingOp::Kind kind, const QString& desktopId, int position, const QString& name) const;
450 void ledgerAdd(PendingOp op);
451 void stopLedgerTimerIfIdle();
452 void expireLedger();
455 void announceIfQuiet(bool wasPending);
458 void noteCreateSucceeded();
460 void noteCreateLanded();
462 bool hasPendingRemove(const QString& desktopId) const;
464 bool hasPendingCreate(const QString& screenId) const;
466 int pendingCreateCount() const;
470 int knownDesktopCount() const;
473 int matchCreateEcho(int position, const QString& name) const;
480 QHash<QString, PendingOp> takeSettledCreates(const QStringList& newIds);
485 bool realizeCreate(const PendingOp& op, const QString& desktopId);
488 bool maintainInvariants();
489 bool maintainScreen(const QString& screenId);
490 void scheduleDestroyCheck(const QString& desktopId);
494 bool isReapable(const QString& desktopId) const;
497 void requestCreateAt(const QString& screenId, int declaredPosition, const QString& name,
498 const QString& namedId = QString());
502 uint kwinPositionForInsert(const QString& screenId, int sliceIndex) const;
503 bool isDesktopEmpty(const QString& desktopId) const;
504 bool isShown(const QString& desktopId) const;
506 QString trailingEmptyOf(const QString& screenId) const;
509 int insertIndexBeforeTrailingEmpty(const QString& screenId) const;
513 int namedSliceIndex(const QString& screenId, int declaredPosition) const;
516 int kwinOrderedSlot(const QString& screenId, const QString& desktopId) const;
519 QString adoptionTarget() const;
528 bool adoptExternal(const QString& desktopId);
532 bool transferExternalToShowingScreen(const QString& desktopId);
535 QSet<QString> migrateHome(const QString& screenId);
536 void setCurrentFor(const QString& screenId, const QString& desktopId);
537 void bumpGeneration();
542 void evaluateForeign(const QString& screenId);
543 void evaluateForeignAll();
544 QString defaultDesktopName(int oneBasedPosition) const;
547 bool isPositionalLabel(const QString& name) const;
550 bool pushDesktopName(const QString& desktopId, const QString& name);
553 void refreshPositionalLabels();
554
555 WorkspaceMap m_map;
556 quint64 m_generation = 0;
557 bool m_adopted = false;
558 QElapsedTimer m_clock;
559 int m_ledgerTimeoutMs = LedgerTimeoutMs;
560 int m_destroyDebounceMs = DestroyDebounceMs;
561 QStringList m_lastIds;
563 QStringList m_lastRawNames;
564 QHash<QString, int> m_population;
567 QHash<QString, QString> m_currentIdByScreen;
570 QHash<QString, int> m_pendingReportByScreen;
572 QHash<QString, QString> m_lastOwnedByScreen;
573 QString m_focusedScreen;
574 std::function<QString()> m_focusedScreenProvider;
575 std::function<QString(int)> m_defaultNameProvider;
576 int m_configuredCap = DefaultDesktopCap;
577 int m_desktopCap = DefaultDesktopCap;
578 bool m_capHintShown = false;
579 QList<PendingOp> m_ledger;
580 QTimer m_ledgerTimer;
581 QHash<QString, QTimer*> m_destroyTimers;
585 QSet<QString> m_racedDesktops;
586 struct NamePush
587 {
588 QString name;
589 qint64 deadline = 0;
590 int refusals = 0;
591 };
597 QHash<QString, NamePush> m_namePushes;
600 QHash<QString, QString> m_reportedKWinRenames;
604 QHash<QString, int> m_removalRefusals;
606 QHash<QString, int> m_createRefusals;
608 QHash<QString, int> m_namedCreateRefusals;
611 QHash<QString, int> m_setCurrentRefusals;
615 QStringList m_capProbeIds;
616 int m_capProbeExpiries = 0;
620 QHash<QString, qint64> m_recentExternal;
623 QList<WorkspaceEntry> m_parked;
625 QSet<QString> m_pinDeferredLogged;
630 QList<NamedWorkspace> m_declarations;
631};
632
633} // namespace PhosphorWorkspaces
The per-monitor workspace ownership model: screenId → ordered slice of KWin desktop ids,...
Definition WorkspaceMap.h:49
void resyncRequested()
A ledger entry expired; controller should re-pull authoritative state.
void onRemoveDesktopAnswered(const QString &desktopId, bool answered)
KWin's answer to one of our removeDesktop calls.
void setFocusedScreenProvider(std::function< QString()> provider)
Pull provider for the focused screen, asked at the moment a desktop needs a home.
void requestSetCurrent(const QString &screenId, const QString &desktopId)
QString desktopIdAtOffsetFrom(const QString &screenId, const QString &fromDesktopId, int delta) const
Like desktopIdAtOffset, counted from fromDesktopId instead of the current desktop.
void requestCreateDesktop(uint position, const QString &name)
Create a desktop at a 0-based position.
void mapChanged()
Map mutated (any structural or metadata change), or a settle moved the published 1-based positions.
static constexpr int MaxRemovalRefusals
How many times a removal KWin never answered is re-armed before the desktop is left alone.
Definition WorkspaceReconciler.h:79
QString inFlightSetCurrentTarget(const QString &screenId) const
The target of the screen's open per-screen switch, or empty.
void requestSetDesktopName(const QString &desktopId, const QString &name)
Sync a desktop's KWin name (named-workspace claim, rename, revert to KWin's positional default).
void onScreenOrderChanged(const QStringList &order)
Screen order recomputed by the controller (geometry left-to-right).
void namedWorkspaceMoved(const QString &namedId, const QString &name, const QString &screenId, int sliceIndex)
A verb moved a named workspace (reorder within its slice, or transfer to another screen).
static constexpr int MaxNamePushRefusals
The probe concludes on its CapProbeExpiries-th expiry, and every expiry before that one has to be fol...
Definition WorkspaceReconciler.h:122
void removalAbandoned(const QString &desktopId)
Our removeDesktop for desktopId expired unanswered, or KWin answered it without removing anything (on...
void onCreateDesktopAnswered(uint position, const QString &name, bool answered)
KWin's answer to one of our createDesktop calls, with the call's own arguments (VirtualDesktopManager...
void onScreenAdded(const QString &screenId)
static constexpr int CapProbeExpiries
How many Create expiries in one episode (the id list unchanged throughout) it takes before the ceilin...
Definition WorkspaceReconciler.h:110
bool reorderCurrentWorkspace(const QString &screenId, int delta)
Reorder the screen's CURRENT workspace within its slice by delta.
QString transferCurrentWorkspace(const QString &screenId, const QString &targetScreenId)
Re-own the screen's current workspace to targetScreenId, inserted before that screen's trailing empty...
static constexpr int MaxCreateRefusals
How many expiry passes in which a screen's unnamed create went unanswered before that screen stops as...
Definition WorkspaceReconciler.h:90
bool issueSetCurrent(const QString &screenId, const QString &desktopId)
Issue a ledgered per-screen switch (focus verbs and snap-back).
bool issueSetCurrentReplacing(const QString &screenId, const QString &desktopId)
Issue a per-screen switch for a navigation verb, REPLACING an open one that was also issued through t...
void onPopulationChanged(const QString &desktopId, int windowCount)
Window population for a desktop id changed (controller-maintained).
void onScreenRenamed(const QString &fromScreenId, const QString &toScreenId)
A screen's id changed while the output stayed connected (a bare id flipping to its connector-qualifie...
bool snapBack(const QString &screenId)
Owner-wins correction: return screenId to its last-shown owned desktop (fallback: its slice head).
static constexpr int DestroyDebounceMs
Definition WorkspaceReconciler.h:72
QHash< QString, int > currentIndexByScreen() const
Every screen's current desktop as a 1-based position in the settled list, for the state file.
WorkspaceReconciler(QObject *parent=nullptr)
void onScreenRemoved(const QString &screenId)
void onKwinDesktopRenamed(const QString &desktopId, const QString &rawName)
KWin's raw name for a desktop changed (VirtualDesktopManager:: desktopRenamed), including the echo of...
void capReached()
The desktop cap stopped a create (once per episode).
static constexpr int DefaultDesktopCap
KWin's desktop ceiling (VirtualDesktopManager::maximum(), 25 in KWin 6.8).
Definition WorkspaceReconciler.h:104
bool isAdopted() const
True once adoptAll has accepted a world.
static constexpr int MaxSetCurrentRefusals
How many per-screen corrections went unechoed or were refused before that screen's owner-wins correct...
Definition WorkspaceReconciler.h:96
QString desktopIdAtSliceIndex(const QString &screenId, int sliceIndex) const
The id at 0-based position sliceIndex of the screen's slice, or empty.
void setFocusedScreen(const QString &screenId)
Fallback for the screen that adopts externally created desktops and realizes unpinned named workspace...
void removalRaceDetected(const QString &desktopId, const QString &ownerScreenId)
A window populated desktopId while our removeDesktop for it was in flight (plan §4....
QString desktopIdAtOffset(const QString &screenId, int delta) const
The id delta slots up (-1) / down (+1) from the screen's current desktop WITHIN ITS OWN SLICE (foreig...
void onKwinDesktopRemoved(const QString &desktopId)
Early id-only echo of a KWin desktop removal.
void onKwinDesktopCreated(const QString &desktopId)
Early id-only echo of a KWin desktop creation (position and name unknown); matches the oldest open cr...
void applyNamedWorkspaces(const QList< NamedWorkspace > &declarations, const QStringList &kwinNames)
Reconcile the declared named workspaces against the map (called after adoption and on every declarati...
bool onScreenDesktopReport(const QString &screenId, int desktop)
A screen's current desktop report (1-based int, effect path), resolved at once against the settled id...
bool adoptAll(const QStringList &ids, const QHash< QString, QString > &currentDesktopIdByScreen, const QHash< QString, QString > &preferredScreenByDesktopId={}, const QStringList &rawNames={})
First-run / restart adoption (plan §4.3): distribute ids (KWin global order) over screens given each ...
bool hasPendingStructuralOps() const
True while any structural op (create/remove) is open or echoed but not yet settled — verb execution d...
const WorkspaceMap & map() const
static constexpr int LedgerTimeoutMs
Definition WorkspaceReconciler.h:71
void onKwinDesktopCreatedAt(const QString &desktopId, int position, const QString &name)
Echo of a KWin desktop creation with KWin's own position (0-based) and name, as its desktopCreated si...
void onScreenDesktopSeeded(const QString &screenId, int desktop)
A screen's current desktop as seeded rather than switched to (a replug or an id rename re-reporting w...
int desktopCap() const
KWin's desktop-count ceiling as the reconciler currently believes it.
void setDefaultDesktopNameProvider(std::function< QString(int)> provider)
KWin's default label for the desktop at a 1-based position (KWin's own defaultName(),...
void setTimeouts(int ledgerTimeoutMs, int destroyDebounceMs)
Ledger expiry and destroy debounce, in milliseconds.
bool restoreState(const QString &json, const std::function< QString(const QString &)> &canonicalScreenId={})
Load a state-file payload as the candidate map adoption reconciles.
void structuralOpsSettled()
hasPendingStructuralOps() just turned false: the settled list now reflects every create and remove th...
QString currentDesktopIdOf(const QString &screenId) const
The desktop id a screen currently shows, as last reported and carried across renumbers by id; empty w...
void namedWorkspaceRenamedInKWin(const QString &namedId, const QString &desktopId, const QString &kwinName)
KWin carries a user-chosen name for a named workspace's desktop that differs from the declaration and...
void onDesktopListSettled(const QStringList &ids, const QStringList &rawNames={})
Authoritative ordered KWin id list settled (from desktopListChanged).
void requestRemoveDesktop(const QString &desktopId)
void foreignSwitchDetected(const QString &screenId, const QString &desktopId, const QString &ownerScreenId)
An unmatched (external) switch put screenId on a desktop owned by another screen.
void setDesktopCap(int cap)
The configured ceiling.
Definition WindowTrackingService.h:46
One declared named workspace (config-driven; persistent while empty).
Definition WorkspaceReconciler.h:24
QString id
Persistent identity of the declaration, minted by whoever adds it to the config and kept across renam...
Definition WorkspaceReconciler.h:30
int position
Preferred slice index, enforced on every apply; -1 = no preference (created before the trailing empty...
Definition WorkspaceReconciler.h:35
QString outputId
pinned screen; empty = unpinned
Definition WorkspaceReconciler.h:32
QString name
unique, non-empty
Definition WorkspaceReconciler.h:31