diff options
author | Andreas Kling <kling@serenityos.org> | 2021-11-24 13:29:17 +0100 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2021-11-24 13:52:01 +0100 |
commit | 51c4de8774a086a504b346d4505c802fad78480b (patch) | |
tree | 391f1a6297289447b1c0cb2b8ae61ff8836dc58f | |
parent | 9b07e13fb636d1a9af51ae91f6f0fe866adc04a1 (diff) | |
download | serenity-51c4de8774a086a504b346d4505c802fad78480b.zip |
LibGUI: Add GUI::Menu::try_add_action() and try_add_separator()
These are fallible variants that return ErrorOr. :^)
-rw-r--r-- | Userland/Libraries/LibGUI/Menu.cpp | 30 | ||||
-rw-r--r-- | Userland/Libraries/LibGUI/Menu.h | 3 |
2 files changed, 27 insertions, 6 deletions
diff --git a/Userland/Libraries/LibGUI/Menu.cpp b/Userland/Libraries/LibGUI/Menu.cpp index 5d5d70d962..4790a477d9 100644 --- a/Userland/Libraries/LibGUI/Menu.cpp +++ b/Userland/Libraries/LibGUI/Menu.cpp @@ -49,12 +49,21 @@ void Menu::set_icon(const Gfx::Bitmap* icon) m_icon = icon; } -void Menu::add_action(NonnullRefPtr<Action> action) +ErrorOr<void> Menu::try_add_action(NonnullRefPtr<Action> action) { - auto item = make<MenuItem>(m_menu_id, move(action)); + // NOTE: We grow the vector first, to get allocation failure handled immediately. + TRY(m_items.try_ensure_capacity(m_items.size() + 1)); + + auto item = TRY(adopt_nonnull_own_or_enomem(new (nothrow) MenuItem(m_menu_id, move(action)))); if (m_menu_id != -1) realize_menu_item(*item, m_items.size()); - m_items.append(move(item)); + m_items.unchecked_append(move(item)); + return {}; +} + +void Menu::add_action(NonnullRefPtr<Action> action) +{ + MUST(try_add_action(move(action))); } Menu& Menu::add_submenu(const String& name) @@ -69,12 +78,21 @@ Menu& Menu::add_submenu(const String& name) return submenu; } -void Menu::add_separator() +ErrorOr<void> Menu::try_add_separator() { - auto item = make<MenuItem>(m_menu_id, MenuItem::Type::Separator); + // NOTE: We grow the vector first, to get allocation failure handled immediately. + TRY(m_items.try_ensure_capacity(m_items.size() + 1)); + + auto item = TRY(adopt_nonnull_own_or_enomem(new (nothrow) MenuItem(m_menu_id, MenuItem::Type::Separator))); if (m_menu_id != -1) realize_menu_item(*item, m_items.size()); - m_items.append(move(item)); + m_items.unchecked_append(move(item)); + return {}; +} + +void Menu::add_separator() +{ + MUST(try_add_separator()); } void Menu::realize_if_needed(const RefPtr<Action>& default_action) diff --git a/Userland/Libraries/LibGUI/Menu.h b/Userland/Libraries/LibGUI/Menu.h index 833c905aa1..8b2b8dccea 100644 --- a/Userland/Libraries/LibGUI/Menu.h +++ b/Userland/Libraries/LibGUI/Menu.h @@ -32,6 +32,9 @@ public: Action* action_at(size_t); + ErrorOr<void> try_add_action(NonnullRefPtr<Action>); + ErrorOr<void> try_add_separator(); + void add_action(NonnullRefPtr<Action>); void add_separator(); Menu& add_submenu(const String& name); |