From f7c4d19df66c602d74795e98ce2ee4390d06fbb4 Mon Sep 17 00:00:00 2001 From: Yuqian Yang Date: Mon, 17 Nov 2025 13:52:52 +0800 Subject: Harden delete after free. --- src/ui/controls/Control.cpp | 17 +++++++++++++++-- src/ui/controls/Window.cpp | 33 +++++++++++++++++++++++---------- 2 files changed, 38 insertions(+), 12 deletions(-) (limited to 'src/ui/controls') diff --git a/src/ui/controls/Control.cpp b/src/ui/controls/Control.cpp index e903b5b3..9c0fc537 100644 --- a/src/ui/controls/Control.cpp +++ b/src/ui/controls/Control.cpp @@ -1,4 +1,5 @@ #include "cru/ui/controls/Control.h" +#include "cru/base/log/Logger.h" #include "cru/ui/controls/Window.h" #include "cru/platform/gui/Cursor.h" @@ -27,11 +28,14 @@ Control::Control() { Control::~Control() { if (auto window = GetWindow()) { if (window->IsInEventHandling()) { - // Don't delete control during event handling. Use DeleteLater. - std::terminate(); + CRU_LOG_TAG_WARN( + "Better use delete later to delete control during event handling."); } } + if (auto window = GetWindow()) { + window->NotifyControlDestroyed(this); + } RemoveFromParent(); } @@ -58,6 +62,15 @@ void Control::SetParent(Control* parent) { OnParentChanged(old_parent, parent); } +bool Control::HasAncestor(Control* control) { + auto parent = this; + while (parent) { + if (parent == control) return true; + parent = parent->GetParent(); + } + return false; +} + void Control::RemoveFromParent() { if (parent_) { parent_->RemoveChild(this); diff --git a/src/ui/controls/Window.cpp b/src/ui/controls/Window.cpp index e6abc48d..c82b2485 100644 --- a/src/ui/controls/Window.cpp +++ b/src/ui/controls/Window.cpp @@ -265,16 +265,6 @@ void Window::SetOverrideCursor(std::shared_ptr cursor) { bool Window::IsInEventHandling() { return event_handling_count_; } -void Window::UpdateCursor() { - if (override_cursor_) { - native_window_->SetCursor(override_cursor_); - } else { - const auto capture = GetMouseCaptureControl(); - native_window_->SetCursor( - (capture ? capture : GetMouseHoverControl())->GetInheritedCursor()); - } -} - void Window::OnNativeDestroy(platform::gui::INativeWindow* window, std::nullptr_t) { CRU_UNUSED(window) @@ -428,4 +418,27 @@ void Window::DispatchMouseHoverControlChangeEvent(Control* old_control, } } +void Window::UpdateCursor() { + if (override_cursor_) { + native_window_->SetCursor(override_cursor_); + } else { + const auto capture = GetMouseCaptureControl(); + native_window_->SetCursor( + (capture ? capture : GetMouseHoverControl())->GetInheritedCursor()); + } +} + +void Window::NotifyControlDestroyed(Control* control) { + if (focus_control_->HasAncestor(control)) { + focus_control_ = control->GetParent(); + } + + if (mouse_captured_control_->HasAncestor(control)) { + mouse_captured_control_ = control->GetParent(); + } + + if (mouse_hover_control_->HasAncestor(control)) { + mouse_hover_control_ = control->GetParent(); + } +} } // namespace cru::ui::controls -- cgit v1.2.3