#pragma once #include "ishaders.h" #include "util/ScopedBoolLock.h" #include namespace ui { template class Binding { private: Source _source; public: using Ptr = std::shared_ptr; virtual ~Binding() {} const Source& getSource() const { return _source; } void setSource(const Source& source) { _source = source; onSourceChanged(); } virtual void updateFromSource() = 0; protected: virtual void onSourceChanged() {} }; // Target selection, usually the Source type is identical to the target type template struct TargetSelector { using TargetType = Source; static TargetType CastToTarget(const Source& source) { return source; } }; // Specialisation for shader layer editing, where the target type is an IEditableShaderLayer template<> struct TargetSelector { using TargetType = IEditableShaderLayer::Ptr; static TargetType CastToTarget(const IShaderLayer::Ptr& source) { return std::static_pointer_cast(source); } }; template class TwoWayBinding : public Binding { public: // Select target: will map Material => Material, but IShaderLayer => IEditableShaderLayer using Target = typename TargetSelector::TargetType; using LoadFunc = std::function; using UpdateFunc = std::function; using AcquireTargetFunc = std::function; using PostUpdateFunc = std::function; protected: LoadFunc _loadValue; AcquireTargetFunc _acquireTarget; UpdateFunc _updateValue; PostUpdateFunc _postUpdate; protected: bool _blockUpdates; protected: TwoWayBinding(const LoadFunc& loadValue, const UpdateFunc& updateValue, const PostUpdateFunc& postChangeNotify = PostUpdateFunc(), const AcquireTargetFunc& acquireTarget = AcquireTargetFunc()) : _loadValue(loadValue), _acquireTarget(acquireTarget), _updateValue(updateValue), _postUpdate(postChangeNotify), _blockUpdates(false) {} Target getTarget() { if (_blockUpdates) { return Target(); } if (std::is_same::value) { return TargetSelector::CastToTarget(Binding::getSource()); } return _acquireTarget ? _acquireTarget() : Target(); } protected: // Just load the given value into the control virtual void setValueOnControl(const ValueType& value) = 0; virtual void updateFromSource() override { util::ScopedBoolLock lock(_blockUpdates); if (!Binding::getSource()) { setValueOnControl(ValueType()); return; } setValueOnControl(_loadValue(Binding::getSource())); } virtual void updateValueOnTarget(const ValueType& newValue) { auto target = getTarget(); if (target) { _updateValue(target, newValue); if (_postUpdate) { _postUpdate(); } } } }; }