From d4e834f734b562c39b08bc2b8b9ca2eb85ac6127 Mon Sep 17 00:00:00 2001 From: apio Date: Wed, 27 Sep 2023 18:51:38 +0200 Subject: [PATCH] libui: Add Actions This allows components like Buttons to take in capturing lambdas --- libui/include/ui/Action.h | 68 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 libui/include/ui/Action.h diff --git a/libui/include/ui/Action.h b/libui/include/ui/Action.h new file mode 100644 index 00000000..4955ffd4 --- /dev/null +++ b/libui/include/ui/Action.h @@ -0,0 +1,68 @@ +#pragma once +#include + +namespace ui +{ + class Action + { + public: + Action() + { + m_action = nullptr; + } + + Action(Action&& other) : m_action(other.m_action) + { + other.m_action = nullptr; + } + + template Action(T&& function) + { + m_action = new (std::nothrow) ActionImpl(move(function)); + } + + template Action& operator=(T&& function) + { + if (m_action) delete m_action; + m_action = new (std::nothrow) ActionImpl(move(function)); + return *this; + } + + void operator()() + { + check(m_action); + return m_action->call(); + } + + ~Action() + { + if (m_action) delete m_action; + } + + private: + class ActionBase + { + public: + virtual void call() = 0; + virtual ~ActionBase() = default; + }; + + template class ActionImpl final : public ActionBase + { + public: + ActionImpl(T&& function) : m_function(move(function)) + { + } + + void call() + { + return m_function(); + } + + private: + T m_function; + }; + + ActionBase* m_action; + }; +}