Support ui:🪟:on_close

This commit is contained in:
Nikita Lisitsa 2021-07-17 17:44:41 +03:00
parent 63ef539303
commit 188f840372
2 changed files with 23 additions and 5 deletions

View file

@ -2,14 +2,19 @@
#include <psemek/ui/element.hpp>
#include <functional>
namespace psemek::ui
{
struct window
: element
{
using on_close_callback = std::function<void()>;
virtual void set_caption(std::string caption) = 0;
virtual std::shared_ptr<element> set_child(std::shared_ptr<element> c) = 0;
virtual void on_close(on_close_callback callback) = 0;
};
}

View file

@ -189,18 +189,24 @@ namespace psemek::ui
children_[0] = caption_.get();
children_[1] = close_button_.get();
children_[2] = nullptr;
on_close_ = [this]
{
if (auto p = dynamic_cast<container *>(parent()))
p->remove_child(this);
else
throw std::runtime_error("Cannot remove window from non-container parent");
};
}
void setup_close()
{
auto weak_self = weak_from_this();
close_button_->on_click([weak_self]{
if (auto self = weak_self.lock())
if (auto self = std::dynamic_pointer_cast<window_impl>(weak_self.lock()))
{
if (auto p = dynamic_cast<container *>(self->parent()))
p->remove_child(self.get());
else
throw std::runtime_error("Cannot remove window from non-container parent");
if (self->on_close_)
self->on_close_();
}
});
}
@ -224,6 +230,11 @@ namespace psemek::ui
return children_range{children_};
}
void on_close(on_close_callback callback) override
{
on_close_ = std::move(callback);
}
bool on_event(mouse_move const & e)
{
mouse_ = e.position;
@ -337,6 +348,8 @@ namespace psemek::ui
std::shared_ptr<rich_button> close_button_;
std::shared_ptr<element> child_;
on_close_callback on_close_;
std::optional<geom::point<int, 2>> mouse_;
std::optional<geom::point<int, 2>> drag_;