1// Aseprite
2// Copyright (C) 2022 Igara Studio S.A.
3//
4// This program is distributed under the terms of
5// the End-User License Agreement for Aseprite.
6
7#ifdef HAVE_CONFIG_H
8#include "config.h"
9#endif
10
11#include "app/app_menus.h"
12#include "app/commands/command.h"
13#include "app/commands/new_params.h"
14#include "app/context.h"
15#include "app/i18n/strings.h"
16#include "fmt/format.h"
17
18namespace app {
19
20struct ShowMenuParams : public NewParams {
21 Param<std::string> menu { this, "", "menu" };
22};
23
24class ShowMenuCommand : public CommandWithNewParams<ShowMenuParams> {
25public:
26 ShowMenuCommand();
27
28protected:
29 bool onNeedsParams() const override { return true; }
30 void onExecute(Context* ctx) override;
31 std::string onGetFriendlyName() const override;
32
33 MenuItem* findMenuItem() const;
34 void openSubmenuById(Menu* menu, const std::string& id);
35};
36
37ShowMenuCommand::ShowMenuCommand()
38 : CommandWithNewParams<ShowMenuParams>(CommandId::ShowMenu(), CmdUIOnlyFlag)
39{
40}
41
42void ShowMenuCommand::onExecute(Context* ctx)
43{
44 if (!ctx->isUIAvailable())
45 return;
46
47 if (MenuItem* menuitem = findMenuItem())
48 menuitem->openSubmenu();
49}
50
51std::string ShowMenuCommand::onGetFriendlyName() const
52{
53 std::string name;
54 if (MenuItem* menuitem = findMenuItem())
55 name = menuitem->text();
56 else
57 name = params().menu();
58 return fmt::format(Strings::commands_ShowMenu(), name);
59}
60
61MenuItem* ShowMenuCommand::findMenuItem() const
62{
63 std::string id = params().menu();
64 if (id.empty())
65 return nullptr;
66
67 if (AppMenus* menus = AppMenus::instance()) {
68 if (Menu* root = menus->getRootMenu()) {
69 if (auto menuitem = root->findItemById(id.c_str())) {
70 if (menuitem->type() == ui::kMenuItemWidget)
71 return static_cast<MenuItem*>(menuitem);
72 }
73 }
74 }
75 return nullptr;
76}
77
78Command* CommandFactory::createShowMenuCommand()
79{
80 return new ShowMenuCommand;
81}
82
83} // namespace app
84