Phosphor
Qt6 / Wayland library suite for window-management tools
Loading...
Searching...
No Matches
PaletteStore.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 <PhosphorTheme/phosphortheme_export.h>
7
8#include <QColor>
9#include <QObject>
10#include <QString>
11#include <QVariantMap>
12#include <QtQmlIntegration/qqmlintegration.h>
13
14#include <memory>
15#include <optional>
16
17class QFileSystemWatcher;
18// QJsonDocument is referenced only by the class's private member
19// signatures (applyParsedJson, applyParsedDocWithLoadError,
20// extractTokensOrEmpty, extractValidTokens). C++ requires non-nested
21// forward declarations at global / namespace scope rather than inside
22// a class body, so it can't live in the `private:` section literally.
23// Grouped here with the other private-only Qt forward decls
24// (QFileSystemWatcher, QTimer — both private members) to keep the
25// "private-API consumer" relationship obvious to readers scanning
26// the file top.
27class QJsonDocument;
28class QTimer;
29
30namespace PhosphorTheme {
31
32// Concrete IThemeService backed by an in-memory QVariantMap. JSON files are
33// loaded eagerly and watched for hot-reload; the file's `tokens` object
34// (token name → "#RRGGBB" or "#AARRGGBB") merges into the active palette
35// (existing tokens absent from the new payload survive) and
36// `paletteChanged` fires once per reload that actually changed at least
37// one token. Use `resetToDefaults()` for a true replace-with-defaults.
38//
39// Path handling: `loadFromFile(path)` canonicalises through
40// QFileInfo::canonicalFilePath() before storing as the watched source,
41// so symlinks are resolved to their target. A passed-in symlink to a
42// palette file will have the underlying target file watched, not the
43// symlink itself. This is by design: hot-reload should track the file
44// whose contents change, not an indirection that may swap targets
45// without notifying the watcher. When canonicalFilePath() returns
46// empty (the path doesn't exist yet, or canonicalisation can't
47// resolve the target), loadFromFile falls back to
48// QFileInfo::absoluteFilePath() so the subsequent open() still
49// surfaces the user-visible path in any error message. No base-dir
50// restriction is applied; callers pass paths they trust (KCM, demo,
51// scripted setup).
52//
53// QML side: registered as a QML singleton via `QML_ELEMENT QML_SINGLETON`,
54// imported as `import Phosphor.Theme` → `PaletteStore.token("primary")`.
55// QML files in Phosphor.Theme (Theme.qml, etc.) wrap PaletteStore in
56// nicer property aliases so consumers write `Theme.primary` instead of
57// `PaletteStore.token("primary")`.
58//
59// This is a per-engine instance, not a process global. The engine owns
60// the lifetime; alternate implementations swap in via
61// `qmlRegisterSingletonInstance` before module import.
62class PHOSPHORTHEME_EXPORT PaletteStore : public QObject, public IThemeService
63{
64 Q_OBJECT
65 QML_ELEMENT
66 QML_SINGLETON
67
68 // QML-friendly accessor exposing the full token map. Bindings on
69 // `palette` re-evaluate when the active palette changes.
70 Q_PROPERTY(QVariantMap palette READ palette NOTIFY paletteChanged)
71
72 // The currently-watched JSON path, or empty if the active palette
73 // came from `loadFromJson` / defaults.
74 Q_PROPERTY(QString sourcePath READ sourcePath NOTIFY sourcePathChanged)
75
76public:
77 explicit PaletteStore(QObject* parent = nullptr);
78 ~PaletteStore() override;
79 Q_DISABLE_COPY_MOVE(PaletteStore)
80
81 // The canonical built-in dark palette. Static accessor for callers
82 // that need the defaults without paying for a PaletteStore instance
83 // (which arms a QFileSystemWatcher + holds an inotify fd). Use this
84 // for preset palettes, snapshot tests, and any read-only consumer.
85 [[nodiscard]] static QVariantMap defaultPalette();
86
87 // IThemeService.
88 [[nodiscard]] QVariantMap palette() const override;
89 [[nodiscard]] Q_INVOKABLE QColor token(const QString& name) const override;
90 // loadFromJson is atomic across ALL three failure modes:
91 // - Parse failure (malformed JSON)
92 // - Shape mismatch (tokens key present but not a JSON object,
93 // mapped to ApplyResult::TokensKeyNotObject)
94 // - No-usable-tokens-found (parsed.isEmpty() after the
95 // QColor-parse pass, mapped to ApplyResult::NoUsableTokens)
96 // On any of these the sourcePath, the watcher, and the active
97 // palette are all unchanged (the implementation validates the
98 // payload up-front, then commits only on success). A previously-
99 // file-loaded store therefore keeps its watcher armed across a
100 // failed loadFromJson call. Callers can treat any false return
101 // as a pure no-op.
102 Q_INVOKABLE bool loadFromJson(const QByteArray& json) override;
103 // loadFromFile is INTENTIONALLY ASYMMETRIC with loadFromJson:
104 // it commits the new sourcePath + swaps the watcher BEFORE
105 // applying the parsed tokens, so a shape-failure return
106 // (`tokens` key non-object, empty token map) still leaves
107 // sourcePath pointing at the new file and the watcher armed
108 // against it. Rationale: those failures are recoverable in
109 // the user's editor without re-triggering load — the file
110 // exists, the JSON parses, the contents just had no usable
111 // tokens. Keeping the watcher armed means the next save in
112 // the editor reloads automatically. Outright parse failures
113 // (malformed JSON) still leave sourcePath untouched because
114 // the parse runs before any commit. Outright I/O failures
115 // (cannot open, short read) also leave sourcePath untouched
116 // for the same reason — loadFromFile performs ONE read of
117 // the file (preflight), parses the bytes into a
118 // QJsonDocument, then threads that document directly into
119 // the apply step. There is no second open/read after
120 // sourcePath is committed, so an unlink-or-truncate race
121 // between the preflight close and the apply step cannot
122 // surface an I/O failure with sourcePath already mutated.
123 // Callers that need atomic-commit semantics across every
124 // failure mode should validate the file out-of-band and
125 // route through loadFromJson instead.
126 //
127 // Note: on shape-failure paths (TokensKeyNotObject /
128 // NoUsableTokens) the new sourcePath is still committed before
129 // the failure surfaces, so `sourcePathChanged` may fire even
130 // when this returns false. QML bindings observing both
131 // sourcePath and loadError must be prepared to see the new
132 // path arrive together with a loadError on the same edit.
133 Q_INVOKABLE bool loadFromFile(const QString& path) override;
134 // Fire-and-forget by IThemeService design: a token map that
135 // normalises to zero usable colors is a no-op rather than an
136 // error. The underlying applyPalette() returns a bool reporting
137 // whether any token changed, but that signal is not propagated
138 // through the IThemeService boundary because every QML/script
139 // caller already observes the result via the paletteChanged
140 // signal — duplicating the verdict in the return value would
141 // force the interface to widen without any consumer needing it.
142 Q_INVOKABLE void applyTokens(const QVariantMap& tokens) override;
143 Q_INVOKABLE void resetToDefaults() override;
144
145 [[nodiscard]] QString sourcePath() const;
146
164
165Q_SIGNALS:
168
169 // Fires when `loadFromFile` failed to parse or read the file. The
170 // active palette is unchanged. Wired to the demo's status bar so a
171 // bad save is visible without crashing the shell.
172 void loadError(const QString& path, const QString& reason);
173
174private:
182 enum class ApplyResult {
183 Ok,
184 TokensKeyNotObject,
185 NoUsableTokens,
186 };
202 static QJsonObject extractTokensOrEmpty(const QJsonDocument& doc, ApplyResult& outShapeError);
215 static std::optional<QVariantMap> extractValidTokens(const QJsonDocument& doc, ApplyResult& outError);
216 [[nodiscard]] ApplyResult applyParsedJson(const QJsonDocument& doc);
225 ApplyResult applyParsedDocWithLoadError(const QString& absolutePath, const QJsonDocument& doc);
242 void readParseAndApply(const QString& absolutePath);
248 void dropWatcherAndClearSourcePath();
259 bool applyPalette(const QVariantMap& tokens);
260 void reloadFromCurrentPath();
272 void armWatchesFor(const QString& absolutePath);
280 void rearmFileIfMissing(const QString& path);
285 void rearmDirIfMissing(const QString& path);
286
287 QVariantMap m_palette;
288 QString m_sourcePath;
289 std::unique_ptr<QFileSystemWatcher> m_watcher;
290 std::unique_ptr<QTimer> m_reloadDebounce;
291};
292
293} // namespace PhosphorTheme
Definition IThemeService.h:85
PaletteStore(QObject *parent=nullptr)
void setDebounceIntervalForTest(int ms)
Test-only: override the hot-reload debounce interval (default 80 ms).
QColor token(const QString &name) const override
void loadError(const QString &path, const QString &reason)
QString sourcePath() const
bool loadFromJson(const QByteArray &json) override
static QVariantMap defaultPalette()
bool loadFromFile(const QString &path) override
QVariantMap palette() const override
void resetToDefaults() override
void applyTokens(const QVariantMap &tokens) override
Definition AppearanceLibrary.h:10