Phosphor
Qt6 / Wayland library suite for window-management tools
Loading...
Searching...
No Matches
ApplicationController.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
6#include "phosphorcontrol_export.h"
7
8#include <QHash>
9#include <QList>
10#include <QObject>
11#include <QPointer>
12#include <QSet>
13#include <QString>
14#include <QStringList>
15#include <QUrl>
16#include <QVariantList>
17#include <QtQml/qqmlregistration.h>
18
19#include <functional>
20
21namespace PhosphorControl {
22
23class PageController;
24class StagingDomain;
25
46class PHOSPHORCONTROL_EXPORT ApplicationController : public QObject
47{
48 Q_OBJECT
49 Q_PROPERTY(PhosphorControl::PageRegistry* registry READ registry CONSTANT)
50 Q_PROPERTY(bool dirty READ isDirty NOTIFY dirtyChanged)
51 Q_PROPERTY(QString currentPageId READ currentPageId WRITE setCurrentPageId NOTIFY currentPageIdChanged)
52 Q_PROPERTY(bool canGoBack READ canGoBack NOTIFY historyChanged)
53 Q_PROPERTY(bool canGoForward READ canGoForward NOTIFY historyChanged)
54 Q_PROPERTY(bool applying READ isApplying NOTIFY applyingChanged)
55 Q_PROPERTY(bool discarding READ isDiscarding NOTIFY discardingChanged)
56 QML_NAMED_ELEMENT(ApplicationController)
57 QML_UNCREATABLE("ApplicationController is constructed in C++.")
58
59public:
60 explicit ApplicationController(QObject* parent = nullptr);
62
64
65 bool isDirty() const;
66
70 bool isApplying() const;
73 bool isDiscarding() const;
74
75 QString currentPageId() const;
76 void setCurrentPageId(const QString& id);
77
93 bool canGoBack() const;
94 bool canGoForward() const;
95 Q_INVOKABLE QString goBack();
96 Q_INVOKABLE QString goForward();
97
98private:
102 QString stepHistory(QStringList& from, QStringList& to);
108 bool isUsableHistoryEntry(const QString& id) const;
109
110public:
124 void setPendingAnchor(const QString& pageId, const QString& anchor);
127 Q_INVOKABLE QString takePendingAnchor(const QString& pageId);
128
149 void registerPage(PageController* page, const QString& parentId, const QString& title, const QUrl& qmlSource,
150 const QString& iconSource = QString(), bool isCollapsible = false, bool hasDividerAfter = false,
152 const QString& counterpartId = QString());
153
162 [[nodiscard]] bool isTrackedDomain(const StagingDomain* domain) const;
163
173 bool bindPage(const QString& id, PageController* controller, const QUrl& qmlSource);
174
181 using NavigationHook = std::function<void(const QString& pageId)>;
185 bool setNavigationHook(QObject* owner, NavigationHook hook);
187 void clearNavigationHook(const QObject* owner);
188
195 void attachDomainToPage(StagingDomain* domain, const QString& pageId);
196
205 Q_INVOKABLE QVariantList extensionsFor(const QString& pageId, const QString& slot) const;
206 using ExtensionProvider = std::function<QVariantList(const QString& pageId, const QString& slot)>;
210 bool setExtensionProvider(QObject* owner, ExtensionProvider provider);
213 void clearExtensionProvider(const QObject* owner);
215 void notifyExtensionsChanged(const QString& pageId);
216
227 Q_INVOKABLE QString gotoPreviousPage();
228 Q_INVOKABLE QString gotoNextPage();
229
235 Q_INVOKABLE QStringList parentChainFor(const QString& id) const;
236
243 Q_INVOKABLE QString titlePathFor(const QString& id) const;
246 static QString titlePathSeparator();
247
259 Q_INVOKABLE QStringList dirtyPageIds() const;
260
261public Q_SLOTS:
262 void applyAll();
283
284public:
292
293Q_SIGNALS:
316 void applyAllComplete(bool ok, const QStringList& errors);
318 void discardAllComplete(bool ok, const QStringList& errors);
320 void extensionsChanged(const QString& pageId);
321
322private Q_SLOTS:
323 void onDomainDirtyChanged();
324 void onTrackedDomainDestroyed();
325
326private:
327 void trackDomain(StagingDomain* domain);
328 void untrackDomain(StagingDomain* domain);
330 void pruneAttachments();
331 void recomputeDirty();
337 bool foldDirty();
343 void completeApplyIfDone();
344 void completeDiscardIfDone();
345
346 // All POD-like members default-initialised here for uniformity —
347 // m_registry is created in the ctor's initializer list, parented to
348 // `this`.
349 PageRegistry* m_registry = nullptr;
350 QList<QPointer<StagingDomain>> m_domains;
351 QString m_currentPageId;
354 quint64 m_navigationSerial = 0;
355 NavigationHook m_navigationHook;
356 QPointer<QObject> m_navigationHookOwner;
358 ExtensionProvider m_extensionProvider;
359 QPointer<QObject> m_extensionProviderOwner;
362 QHash<QString, QList<QPointer<StagingDomain>>> m_pageAttachments;
363 // Back/forward navigation history (see canGoBack/goBack). The back
364 // stack's last entry is the page goBack() lands on; symmetric for
365 // the forward stack. m_navigatingHistory suppresses recording while
366 // goBack/goForward drive setCurrentPageId, so history moves don't
367 // re-record themselves.
368 QStringList m_backHistory;
369 QStringList m_forwardHistory;
370 bool m_navigatingHistory = false;
373 static constexpr int MaxHistoryEntries = 64;
374 // Deep-link reveal latch (see setPendingAnchor). Transient; not page identity.
375 QString m_pendingAnchor;
376 QString m_pendingAnchorPage;
377 bool m_dirty = false;
378 // Set during applyAll / discardAll so each inner dirtyChanged →
379 // recomputeDirty edge is suppressed; the outer transaction emits
380 // a single recomputeDirty at the end. Eliminates the O(N²) walk
381 // pattern audit-follow-up A15 flagged.
382 bool m_inTransaction = false;
383 // Re-entrancy guard for recomputeDirty. A subclass that emits
384 // dirtyChanged from inside its isDirty() virtual would otherwise
385 // recursively re-enter the QList::erase loop, undefined behaviour.
386 bool m_recomputingDirty = false;
387 // Set when recomputeDirty is rejected by the re-entrancy guard;
388 // the outer call replays the recompute via a queued invokeMethod
389 // so a cascaded dirty edge isn't silently swallowed.
390 bool m_recomputeDirtyPending = false;
391 // Set when an async completion folded a dirty change before announcing
392 // the batch; the completion emits dirtyChanged after its *Complete
393 // signal unless a recomputeDirty in between already did.
394 bool m_dirtyNotifyPending = false;
395
396 // Async batch state. m_*Pending counts how many domains still
397 // owe an applyResult / discardResult; m_*Errors collects user-
398 // readable failure messages.
399 int m_applyPending = 0;
400 QStringList m_applyErrors;
401 bool m_applying = false;
402 int m_discardPending = 0;
403 QStringList m_discardErrors;
404 bool m_discarding = false;
405 // Monotonic batch generation counters. Bumped at the start of each
406 // *Async batch (and inside forceResetAsyncState) and captured by
407 // every lambda the batch wires — the lambda bails out when its
408 // captured generation no longer matches the live counter. Guards
409 // against ALL stale-callback shapes:
410 // * a 60s timer firing after a previous batch completed and a
411 // new batch is now in flight
412 // * a per-domain applyResult/destroyed lambda from a re-entered
413 // batch decrementing the NEW batch's pending counter
414 // * an applyResult fired after forceResetAsyncState recovered a
415 // wedged batch (the stale lambdas are still wired but the
416 // generation has moved on)
417 quint64 m_applyGeneration = 0;
418 quint64 m_discardGeneration = 0;
419 // Per-batch outstanding domain sets. A domain is in the set when
420 // we still expect EXACTLY ONE more terminal signal (applyResult
421 // OR destroyed) from it. The first to fire removes the domain;
422 // the second is a no-op. Without this, a domain that emits
423 // applyResult synchronously and is then destroyed later in the
424 // batch would tick the pending counter TWICE (once per signal),
425 // driving it negative and miscounting completion.
426 //
427 // Pointer-deref safety: the per-domain `destroyed` lambda removes
428 // the dying pointer from this set BEFORE the destructor returns,
429 // and the batch-timeout handler (the only other consumer that
430 // dereferences these pointers to read `objectName()`) walks the
431 // set only AFTER all live entries have been processed — by which
432 // point the set contains only pointers to still-live domains.
433 // No dangling deref is reachable along the documented call paths,
434 // but callers that introduce a new consumer of these pointers
435 // MUST honour the same single-threaded "remove-before-destroy"
436 // discipline.
437 QSet<StagingDomain*> m_applyOutstanding;
438 QSet<StagingDomain*> m_discardOutstanding;
439 // Per-batch connection handles for the applyResult / destroyed
440 // (apply path) and discardResult / destroyed (discard path) lambdas.
441 // Cleared and disconnected at terminal emit in completeApplyIfDone /
442 // completeDiscardIfDone so dead lambdas don't accumulate on domains
443 // that completed this batch but never participate in subsequent
444 // batches. Qt::SingleShotConnection self-disconnects only on actual
445 // fire; the destroyed() lambda for a long-lived domain would
446 // otherwise stay wired across every batch's lifetime.
447 QList<QMetaObject::Connection> m_applyConnections;
448 QList<QMetaObject::Connection> m_discardConnections;
453 static constexpr int DefaultAsyncBatchTimeoutMs = 60'000;
454 int m_asyncBatchTimeoutMs = DefaultAsyncBatchTimeoutMs;
455};
456
457} // namespace PhosphorControl
std::function< void(const QString &pageId)> NavigationHook
Called with the target page id when setCurrentPageId moves to a known page other than the current one...
Definition ApplicationController.h:181
void applyAllAsync()
Async variant of applyAll — collects each dirty domain's applyResult signal and emits applyAllComplet...
void discardAllAsync()
Symmetric to applyAllAsync; emits discardAllComplete(ok, errors).
int asyncBatchTimeoutMs() const
Async-batch timeout in milliseconds, DefaultAsyncBatchTimeoutMs by default: generous for D-Bus round ...
std::function< QVariantList(const QString &pageId, const QString &slot)> ExtensionProvider
Definition ApplicationController.h:206
void discardingChanged()
Symmetric to applyingChanged for discardAllAsync.
void clearExtensionProvider(const QObject *owner)
Remove the provider if owner installed it.
QString takePendingAnchor(const QString &pageId)
Returns + clears the pending anchor iff it targets pageId; otherwise returns an empty string (consume...
QString titlePathFor(const QString &id) const
The page's title path: every ancestor title root-first, then the page's own title,...
void setCurrentPageId(const QString &id)
void forceResetAsyncState()
Force-reset the async-batch state machine to idle.
bool isDiscarding() const
True while discardAllAsync is in flight — symmetric with isApplying.
bool bindPage(const QString &id, PageController *controller, const QUrl &qmlSource)
Give the already-registered page id its real controller and QML source (PageRegistry::bindPage,...
bool canGoBack() const
Browser-style navigation history over currentPageId.
bool setExtensionProvider(QObject *owner, ExtensionProvider provider)
Install provider on behalf of owner.
void historyChanged()
Emitted when canGoBack / canGoForward may have flipped (shared NOTIFY for both properties — they alwa...
void extensionsChanged(const QString &pageId)
The sections added to page pageId changed (notifyExtensionsChanged).
void setPendingAnchor(const QString &pageId, const QString &anchor)
Deep-link reveal latch (generic — every settings app built on this shell gets deep-link-to-anchor for...
QStringList dirtyPageIds() const
Ids of every registered page whose controller, or a domain attached to it (attachDomainToPage),...
void discardAllComplete(bool ok, const QStringList &errors)
Symmetric to applyAllComplete for discardAllAsync.
void clearNavigationHook(const QObject *owner)
Remove the hook if owner installed it. A no-op otherwise.
bool registerDomain(StagingDomain *domain)
Register a headless staging domain (no sidebar entry).
QStringList parentChainFor(const QString &id) const
Walk the parent chain from the registered entry for id to the top level.
void applyingChanged()
Emitted on every applying-state transition (false→true at the start of applyAllAsync,...
ApplicationController(QObject *parent=nullptr)
void applyAllComplete(bool ok, const QStringList &errors)
Emitted exactly once per applyAllAsync invocation, when every dirty domain's applyResult has been rec...
QString gotoPreviousPage()
Navigate to the previous / next navigable page (one with a qmlSource) in the order the sidebar draws ...
bool setNavigationHook(QObject *owner, NavigationHook hook)
Install hook on behalf of owner.
bool isTrackedDomain(const StagingDomain *domain) const
True iff domain is tracked: a registered page's controller or a registered headless domain.
static QString titlePathSeparator()
The separator between the titles of a page path (U+203A), shared by titlePathFor and SearchController...
void notifyExtensionsChanged(const QString &pageId)
Tell ExtensionSlots on page pageId to read extensionsFor again.
void attachDomainToPage(StagingDomain *domain, const QString &pageId)
Count domain as part of page pageId: dirtyPageIds() lists the page while the domain is dirty,...
void pendingAnchorChanged()
Emitted when the deep-link pending anchor is set or cleared.
QVariantList extensionsFor(const QString &pageId, const QString &slot) const
The sections other modules add to slot slot of page pageId, for the QML ExtensionSlot.
bool isApplying() const
True while applyAllAsync is in flight (at least one domain's applyResult hasn't landed yet).
void registerPage(PageController *page, const QString &parentId, const QString &title, const QUrl &qmlSource, const QString &iconSource=QString(), bool isCollapsible=false, bool hasDividerAfter=false, PageRegistry::PageVisibility visibility=PageRegistry::PageVisibility::Always, const QString &counterpartId=QString())
Register a page in the sidebar.
Base class for a settings page: a staging domain backed by a QML page that appears in the sidebar.
Definition PageController.h:24
Holds the catalogue of pages an application has registered.
Definition PageRegistry.h:46
PageVisibility
Master toggle for the two-tier "simple vs advanced" sidebar.
Definition PageRegistry.h:70
@ Always
Definition PageRegistry.h:71
Abstract base for anything that holds staged user changes pending an Apply.
Definition StagingDomain.h:30
Definition ApplicationController.h:21