QmlMaterial 0.1.0
Loading...
Searching...
No Matches
state_bindings.hpp
1#pragma once
2
3#include <QDebug>
4#include <QPointer>
5#include <QProperty>
6#include <algorithm>
7#include <functional>
8#include <map>
9#include <memory>
10#include <optional>
11#include <typeindex>
12#include <utility>
13#include <vector>
14
15namespace qml_material
16{
17namespace detail
18{
19struct StateBindingCondition {
20 QProperty<bool> value;
21 QPropertyNotifier notifier;
22};
23
24struct StateBindingOwner {
25 std::function<bool()> alive;
26 bool stopped = false;
27
28 bool isActive() {
29 if (stopped) return false;
30 if (alive && ! alive()) stopped = true;
31 return ! stopped;
32 }
33};
34
35struct StateProperty {
36 QPointer<QObject> owner;
37 std::type_index accessor;
38 std::shared_ptr<StateBindingOwner> lifetime;
39 StateProperty(QObject* object, std::type_index type, std::shared_ptr<StateBindingOwner> guard)
40 : owner(object), accessor(type), lifetime(std::move(guard)) {}
41 virtual ~StateProperty() = default;
42 virtual void apply(std::optional<qint64>) = 0;
43 virtual void abandon() = 0;
44};
45
46template<typename T>
47struct StatePropertyOf : StateProperty {
48 std::function<QBindable<T>()> access;
49 std::map<qint64, QPropertyBinding<T>> overrides;
50 std::vector<std::pair<std::shared_ptr<StateBindingCondition>, QPropertyBinding<T>>> conditions;
51 std::optional<qint64> appliedState;
52 const StateBindingCondition* appliedCondition = nullptr;
53 // Reconstruct handles; Qt 6.11's copy assignment can free the replacement binding.
54 std::optional<QPropertyBinding<T>> base, saved;
55 T initial {}, savedValue {};
56 bool covered = false, stopped = false, baseDeclared = false;
57
58 StatePropertyOf(QObject* object, std::type_index type, std::shared_ptr<StateBindingOwner> guard,
59 std::function<QBindable<T>()> getter)
60 : StateProperty(object, type, std::move(guard)), access(std::move(getter)) {
61 if (! isActive()) return;
62 initial = access().value();
63 if (! isActive()) return;
64 const auto binding = access().binding();
65 if (! binding.isNull())
66 base.emplace(binding);
67 else
68 base.emplace(Qt::makePropertyBinding([value = initial] {
69 return value;
70 }));
71 }
72
73 bool isActive() {
74 if (! stopped && owner && lifetime->isActive() && owner && ! stopped) return true;
75 abandon();
76 return false;
77 }
78
79 void install(QPropertyBinding<T> binding) {
80 if (! isActive()) return;
81 access().setBinding(binding);
82 }
83
84 void reset() {
85 if (! isActive()) return;
86 if (! base)
87 access().setValue(initial);
88 else
89 install(*base);
90 }
91
92 void apply(std::optional<qint64> state) override {
93 if (! isActive()) return;
94 const auto next = state ? overrides.find(*state) : overrides.end();
95 const auto nextState = next != overrides.end() ? state : std::nullopt;
96 std::optional<QPropertyBinding<T>> binding;
97 const StateBindingCondition* condition = nullptr;
98 if (next != overrides.end()) {
99 binding.emplace(next->second);
100 } else {
101 const auto candidates = conditions;
102 for (const auto& candidate : candidates) {
103 const bool matches = candidate.first->value.value();
104 if (! isActive()) return;
105 if (matches) {
106 binding.emplace(candidate.second);
107 condition = candidate.first.get();
108 }
109 }
110 }
111 if (binding) {
112 if (covered && appliedState == nextState && appliedCondition == condition) return;
113 const auto replacement = *binding;
114 if (! covered) {
115 const auto original = access().binding();
116 if (! isActive()) return;
117 const auto value = original.isNull() ? access().value() : T {};
118 if (! isActive()) return;
119 saved.emplace(original);
120 savedValue = value;
121 covered = true;
122 }
123 appliedState = nextState;
124 appliedCondition = condition;
125 install(replacement);
126 } else if (covered) {
127 covered = false;
128 appliedState.reset();
129 appliedCondition = nullptr;
130 const auto original = std::move(*saved);
131 saved.reset();
132 const auto value = savedValue;
133 if (! isActive()) return;
134 if (original.isNull())
135 access().setValue(value);
136 else
137 access().setBinding(original);
138 }
139 }
140
141 void abandon() override {
142 stopped = true;
143 saved.reset();
144 base.reset();
145 overrides.clear();
146 conditions.clear();
147 }
148};
149
150struct StateBindingData {
151 std::shared_ptr<StateBindingOwner> lifetime = std::make_shared<StateBindingOwner>();
152 std::vector<std::shared_ptr<StateProperty>> properties;
153 std::map<qint64, std::vector<std::shared_ptr<StateProperty>>> states;
154 std::vector<std::shared_ptr<StateBindingCondition>> conditions;
155 std::optional<qint64> current;
156 std::optional<std::optional<qint64>> pending;
157 bool frozen = false, switching = false, stopped = false, refreshPending = false;
158
159 void abandon() {
160 if (std::exchange(stopped, true)) return;
161 lifetime->stopped = true;
162 for (const auto& condition : conditions) {
163 condition->notifier = {};
164 condition->value.takeBinding();
165 }
166 for (const auto& property : properties) property->abandon();
167 }
168
169 bool isActive() {
170 if (! stopped && lifetime->isActive() && ! stopped) return true;
171 abandon();
172 return false;
173 }
174
175 bool select(std::optional<qint64> next, bool refresh = false) {
176 if (! isActive()) return false;
177 if (switching) {
178 if (! refresh || ! pending) pending.emplace(next);
179 refreshPending |= refresh;
180 return true;
181 }
182 frozen = true;
183 for (int changes = 0; changes < 64; ++changes) {
184 pending.reset();
185 refresh |= std::exchange(refreshPending, false);
186 if (current == next && ! refresh) return true;
187 auto affected =
188 current ? states[*current] : std::vector<std::shared_ptr<StateProperty>> {};
189 if (next) {
190 for (const auto& property : states[*next]) {
191 if (std::find(affected.begin(), affected.end(), property) == affected.end())
192 affected.push_back(property);
193 }
194 }
195 if (refresh) affected = properties;
196 refresh = false;
197 switching = true;
198 current = next;
199 {
200 const QScopedPropertyUpdateGroup group;
201 for (const auto& property : affected) {
202 if (! isActive()) break;
203 property->apply(next);
204 }
205 }
206 switching = false;
207 if (! isActive()) return false;
208 if (! pending) return true;
209 next = *pending;
210 }
211 pending.reset();
212 qWarning("StateBindings: cyclic state changes");
213 return false;
214 }
215};
216
217template<auto Accessor>
218struct AccessorTag {};
219template<typename>
220struct BindableValue;
221template<typename T>
222struct BindableValue<QBindable<T>> {
223 using Type = T;
224};
225} // namespace detail
226
227template<typename T>
228class PropertyKey {
229 template<typename>
230 friend class StateBindingSet;
231 friend class StateBindings;
232 std::weak_ptr<detail::StateBindingData> m_owner;
233 std::shared_ptr<detail::StatePropertyOf<T>> m_property;
234
235public:
236 bool isValid() const {
237 const auto property = m_property;
238 return property && property->isActive();
239 }
240 void reset() const {
241 const auto property = m_property;
242 if (property) property->reset();
243 }
244};
245
246class StateBindings {
247 template<typename>
248 friend class StateBindingSet;
249 std::shared_ptr<detail::StateBindingData> m_data;
250 std::optional<qint64> m_state;
251 std::shared_ptr<detail::StateBindingCondition> m_condition;
252 StateBindings(std::shared_ptr<detail::StateBindingData> data, std::optional<qint64> state,
253 std::shared_ptr<detail::StateBindingCondition> condition = {})
254 : m_data(std::move(data)), m_state(state), m_condition(std::move(condition)) {}
255
256public:
257 template<typename T>
258 bool bind(const PropertyKey<T>& key, const QPropertyBinding<T>& binding) const {
259 const auto data = m_data;
260 if (! data->isActive()) return false;
261 if (data->frozen || data->stopped || key.m_owner.lock() != data || ! key.isValid() ||
262 binding.isNull()) {
263 qWarning("StateBindings: invalid or frozen declaration");
264 return false;
265 }
266 const auto property = key.m_property;
267 if (m_condition) {
268 if (std::any_of(property->conditions.begin(),
269 property->conditions.end(),
270 [this](const auto& candidate) {
271 return candidate.first == m_condition;
272 })) {
273 qWarning("StateBindings: duplicate conditional declaration");
274 return false;
275 }
276 property->conditions.emplace_back(m_condition, binding);
277 property->apply(data->current);
278 } else if (m_state) {
279 if (! property->overrides.emplace(*m_state, binding).second) {
280 qWarning("StateBindings: duplicate property declaration");
281 return false;
282 }
283 data->states[*m_state].push_back(property);
284 } else {
285 if (property->baseDeclared) {
286 qWarning("StateBindings: duplicate base declaration");
287 return false;
288 }
289 property->base.emplace(binding);
290 property->baseDeclared = true;
291 property->install(binding);
292 }
293 return data->isActive();
294 }
295
296 template<typename T, typename F>
297 requires std::is_invocable_r_v<T, F> &&
298 std::is_same_v<std::remove_cvref_t<std::invoke_result_t<F>>, T>
299 bool bind(const PropertyKey<T>& key, F&& function) const {
300 return bind(key, Qt::makePropertyBinding(std::forward<F>(function)));
301 }
302};
303
304template<typename StateId>
305class StateBindingSet {
306 static_assert(std::is_enum_v<StateId>);
307 std::shared_ptr<detail::StateBindingData> m_data = std::make_shared<detail::StateBindingData>();
308 StateId m_base;
309
310public:
311 explicit StateBindingSet(StateId base): m_base(base) {}
312 StateBindingSet(const StateBindingSet&) = delete;
313 StateBindingSet& operator=(const StateBindingSet&) = delete;
314 ~StateBindingSet() { abandon(); }
315
316 // A false result is terminal, even while the property objects still exist.
317 bool setOwnerAliveCheck(std::function<bool()> check) {
318 const auto data = m_data;
319 if (data->frozen || data->stopped || ! data->properties.empty()) {
320 qWarning("StateBindings: owner check must precede property registration");
321 return false;
322 }
323 data->lifetime->alive = std::move(check);
324 return true;
325 }
326
327 template<auto Accessor, typename Object>
328 auto property(Object* object) {
329 using T =
330 typename detail::BindableValue<std::invoke_result_t<decltype(Accessor), Object*>>::Type;
331 PropertyKey<T> key;
332 const auto data = m_data;
333 if (! data->isActive()) return key;
334 if (! object || data->frozen || data->stopped) {
335 qWarning("StateBindings: invalid or frozen property registration");
336 return key;
337 }
338 const auto bindable = std::invoke(Accessor, object);
339 if (! bindable.isValid() || ! bindable.isBindable() || bindable.isReadOnly()) {
340 qWarning("StateBindings: property must be writable and bindable");
341 return key;
342 }
343 const std::type_index type(typeid(detail::AccessorTag<Accessor>));
344 key.m_owner = data;
345 for (const auto& existing : data->properties) {
346 if (existing->owner == object && existing->accessor == type) {
347 key.m_property = std::static_pointer_cast<detail::StatePropertyOf<T>>(existing);
348 return key;
349 }
350 }
351 const auto property =
352 std::make_shared<detail::StatePropertyOf<T>>(object, type, data->lifetime, [object] {
353 return std::invoke(Accessor, object);
354 });
355 if (! data->isActive() || ! property->isActive()) return key;
356 key.m_property = property;
357 data->properties.push_back(property);
358 return key;
359 }
360
361 StateBindings base() const { return { m_data, {} }; }
362 // Explicit states override conditions; otherwise the last matching condition wins per property.
363 StateBindings when(std::function<bool()> predicate) {
364 const auto data = m_data;
365 auto condition = std::make_shared<detail::StateBindingCondition>();
366 if (! data->isActive() || data->frozen) {
367 qWarning("StateBindings: invalid or frozen conditional declaration");
368 return { data, {}, condition };
369 }
370 condition->value.setBinding(std::move(predicate));
371 if (! data->isActive()) return { data, {}, condition };
372 condition->notifier = condition->value.addNotifier([weak = std::weak_ptr(data)] {
373 if (const auto owner = weak.lock()) owner->select(owner->current, true);
374 });
375 data->conditions.push_back(condition);
376 return { data, {}, condition };
377 }
378 StateBindings state(StateId id) const {
379 return { m_data, id == m_base ? std::nullopt : std::optional<qint64>(qint64(id)) };
380 }
381 bool select(StateId id) {
382 const auto data = m_data;
383 return data->select(id == m_base ? std::nullopt : std::optional<qint64>(qint64(id)));
384 }
385 bool detach() {
386 const auto data = m_data;
387 for (const auto& condition : data->conditions) {
388 condition->notifier = {};
389 condition->value = false;
390 }
391 const bool restored = data->select({}, true);
392 data->abandon();
393 return restored;
394 }
395 void abandon() {
396 const auto data = m_data;
397 data->abandon();
398 }
399 class Lifetime {
400 std::shared_ptr<detail::StateBindingData> m_data;
401 friend class StateBindingSet;
402 explicit Lifetime(std::shared_ptr<detail::StateBindingData> data)
403 : m_data(std::move(data)) {}
404
405 public:
406 Lifetime(const Lifetime&) = delete;
407 ~Lifetime() { m_data->abandon(); }
408 };
409 Lifetime lifetime() const { return Lifetime(m_data); }
410};
411} // namespace qml_material