From 188f84037299c705bd37bf4f4a65d76cfd922ce8 Mon Sep 17 00:00:00 2001 From: lisyarus Date: Sat, 17 Jul 2021 17:44:41 +0300 Subject: [PATCH] Support ui::window::on_close --- libs/ui/include/psemek/ui/window.hpp | 5 +++++ libs/ui/source/default_element_factory.cpp | 23 +++++++++++++++++----- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/libs/ui/include/psemek/ui/window.hpp b/libs/ui/include/psemek/ui/window.hpp index 2e651acd..190e4439 100644 --- a/libs/ui/include/psemek/ui/window.hpp +++ b/libs/ui/include/psemek/ui/window.hpp @@ -2,14 +2,19 @@ #include +#include + namespace psemek::ui { struct window : element { + using on_close_callback = std::function; + virtual void set_caption(std::string caption) = 0; virtual std::shared_ptr set_child(std::shared_ptr c) = 0; + virtual void on_close(on_close_callback callback) = 0; }; } diff --git a/libs/ui/source/default_element_factory.cpp b/libs/ui/source/default_element_factory.cpp index 2451074e..da50a9f6 100644 --- a/libs/ui/source/default_element_factory.cpp +++ b/libs/ui/source/default_element_factory.cpp @@ -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(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(weak_self.lock())) { - if (auto p = dynamic_cast(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 close_button_; std::shared_ptr child_; + on_close_callback on_close_; + std::optional> mouse_; std::optional> drag_;