From 571c4d3fb81a64199f94412c078f7dbe6c992236 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Mon, 9 Dec 2019 21:25:48 +0100 Subject: [PATCH] LibGUI: Allow finding the source of a GAction activation When a GAction is activated by a menu, or by a toolbar button, you can now use GAction::activator() to get a pointer to whomever activated it. This can be used to implement context-specific behaviors in situations where the same action is exposed through multiple paths. This addresses an issue that was brought up in #826. --- Libraries/LibGUI/GAction.cpp | 5 ++++- Libraries/LibGUI/GAction.h | 6 +++++- Libraries/LibGUI/GButton.cpp | 2 +- Libraries/LibGUI/GWindowServerConnection.cpp | 2 +- 4 files changed, 11 insertions(+), 4 deletions(-) diff --git a/Libraries/LibGUI/GAction.cpp b/Libraries/LibGUI/GAction.cpp index a8ba924488d..d62ba660e9d 100644 --- a/Libraries/LibGUI/GAction.cpp +++ b/Libraries/LibGUI/GAction.cpp @@ -127,10 +127,13 @@ GAction::~GAction() m_widget->unregister_local_shortcut_action({}, *this); } -void GAction::activate() +void GAction::activate(CObject* activator) { + if (activator) + m_activator = activator->make_weak_ptr(); if (on_activation) on_activation(*this); + m_activator = nullptr; } void GAction::register_button(Badge, GButton& button) diff --git a/Libraries/LibGUI/GAction.h b/Libraries/LibGUI/GAction.h index 285df968dba..58cf4a7c10e 100644 --- a/Libraries/LibGUI/GAction.h +++ b/Libraries/LibGUI/GAction.h @@ -69,9 +69,12 @@ public: const GraphicsBitmap* icon() const { return m_icon.ptr(); } void set_icon(const GraphicsBitmap* icon) { m_icon = icon; } + const CObject* activator() const { return m_activator.ptr(); } + CObject* activator() { return m_activator.ptr(); } + Function on_activation; - void activate(); + void activate(CObject* activator = nullptr); bool is_enabled() const { return m_enabled; } void set_enabled(bool); @@ -117,4 +120,5 @@ private: HashTable m_menu_items; WeakPtr m_widget; WeakPtr m_action_group; + WeakPtr m_activator; }; diff --git a/Libraries/LibGUI/GButton.cpp b/Libraries/LibGUI/GButton.cpp index 1170f35ffd8..c35bbdbb6f0 100644 --- a/Libraries/LibGUI/GButton.cpp +++ b/Libraries/LibGUI/GButton.cpp @@ -69,7 +69,7 @@ void GButton::click() if (on_click) on_click(*this); if (m_action) - m_action->activate(); + m_action->activate(this); } bool GButton::supports_keyboard_activation() const diff --git a/Libraries/LibGUI/GWindowServerConnection.cpp b/Libraries/LibGUI/GWindowServerConnection.cpp index aba2bcdba5b..4867d84954d 100644 --- a/Libraries/LibGUI/GWindowServerConnection.cpp +++ b/Libraries/LibGUI/GWindowServerConnection.cpp @@ -209,7 +209,7 @@ void GWindowServerConnection::handle(const WindowClient::MenuItemActivated& mess return; } if (auto* action = menu->action_at(message.identifier())) - action->activate(); + action->activate(menu); } void GWindowServerConnection::handle(const WindowClient::WM_WindowStateChanged& message)