1 | // Aseprite |
---|---|
2 | // Copyright (C) 2018-2022 Igara Studio S.A. |
3 | // Copyright (C) 2001-2018 David Capello |
4 | // |
5 | // This program is distributed under the terms of |
6 | // the End-User License Agreement for Aseprite. |
7 | |
8 | #ifdef HAVE_CONFIG_H |
9 | #include "config.h" |
10 | #endif |
11 | |
12 | #ifndef ENABLE_SCRIPTING |
13 | #error ENABLE_SCRIPTING must be defined |
14 | #endif |
15 | |
16 | #include "app/app.h" |
17 | #include "app/commands/command.h" |
18 | #include "app/commands/params.h" |
19 | #include "app/console.h" |
20 | #include "app/context.h" |
21 | #include "app/i18n/strings.h" |
22 | #include "app/pref/preferences.h" |
23 | #include "app/resource_finder.h" |
24 | #include "app/script/engine.h" |
25 | #include "app/ui/optional_alert.h" |
26 | #include "base/fs.h" |
27 | #include "fmt/format.h" |
28 | #include "ui/manager.h" |
29 | |
30 | #include <cstdio> |
31 | |
32 | namespace app { |
33 | |
34 | class RunScriptCommand : public Command { |
35 | public: |
36 | RunScriptCommand(); |
37 | |
38 | protected: |
39 | void onLoadParams(const Params& params) override; |
40 | void onExecute(Context* context) override; |
41 | std::string onGetFriendlyName() const override; |
42 | |
43 | private: |
44 | std::string m_filename; |
45 | Params m_params; |
46 | }; |
47 | |
48 | RunScriptCommand::RunScriptCommand() |
49 | : Command(CommandId::RunScript(), CmdRecordableFlag) |
50 | { |
51 | } |
52 | |
53 | void RunScriptCommand::onLoadParams(const Params& params) |
54 | { |
55 | m_filename = params.get("filename"); |
56 | if (base::get_file_path(m_filename).empty()) { |
57 | ResourceFinder rf; |
58 | rf.includeDataDir(base::join_path("scripts", m_filename).c_str()); |
59 | if (rf.findFirst()) |
60 | m_filename = rf.filename(); |
61 | } |
62 | |
63 | m_params = params; |
64 | } |
65 | |
66 | void RunScriptCommand::onExecute(Context* context) |
67 | { |
68 | #if ENABLE_UI |
69 | if (context->isUIAvailable()) { |
70 | int ret = OptionalAlert::show( |
71 | Preferences::instance().scripts.showRunScriptAlert, |
72 | 1, // Yes is the default option when the alert dialog is disabled |
73 | fmt::format(Strings::alerts_run_script(), m_filename)); |
74 | if (ret != 1) |
75 | return; |
76 | } |
77 | #endif // ENABLE_UI |
78 | |
79 | App::instance() |
80 | ->scriptEngine() |
81 | ->evalFile(m_filename, m_params); |
82 | |
83 | #if ENABLE_UI |
84 | if (context->isUIAvailable()) |
85 | ui::Manager::getDefault()->invalidate(); |
86 | #endif |
87 | } |
88 | |
89 | std::string RunScriptCommand::onGetFriendlyName() const |
90 | { |
91 | if (m_filename.empty()) |
92 | return getBaseFriendlyName(); |
93 | else |
94 | return fmt::format("{0}: {1}", |
95 | getBaseFriendlyName(), |
96 | base::get_file_name(m_filename)); |
97 | } |
98 | |
99 | Command* CommandFactory::createRunScriptCommand() |
100 | { |
101 | return new RunScriptCommand; |
102 | } |
103 | |
104 | } // namespace app |
105 |