libui: Add Actions
This allows components like Buttons to take in capturing lambdas
This commit is contained in:
parent
54afd7c2b0
commit
d4e834f734
68
libui/include/ui/Action.h
Normal file
68
libui/include/ui/Action.h
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <luna/Heap.h>
|
||||||
|
|
||||||
|
namespace ui
|
||||||
|
{
|
||||||
|
class Action
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
Action()
|
||||||
|
{
|
||||||
|
m_action = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
Action(Action&& other) : m_action(other.m_action)
|
||||||
|
{
|
||||||
|
other.m_action = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename T> Action(T&& function)
|
||||||
|
{
|
||||||
|
m_action = new (std::nothrow) ActionImpl<T>(move(function));
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename T> Action& operator=(T&& function)
|
||||||
|
{
|
||||||
|
if (m_action) delete m_action;
|
||||||
|
m_action = new (std::nothrow) ActionImpl<T>(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 <typename T> 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;
|
||||||
|
};
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user