Merge branch 'plugin-onenabled'

This commit is contained in:
David Capello 2021-09-30 15:02:14 -03:00
commit 33595c8bbb
2 changed files with 39 additions and 5 deletions

View File

@ -10,6 +10,6 @@
// Increment this value if the scripting API is modified between two
// released Aseprite versions.
#define API_VERSION 14
#define API_VERSION 15
#endif

View File

@ -31,10 +31,13 @@ class PluginCommand : public Command {
public:
PluginCommand(const std::string& id,
const std::string& title,
int onclickRef)
int onclickRef,
int onenabledRef)
: Command(id.c_str(), CmdUIOnlyFlag)
, m_title(title)
, m_onclickRef(onclickRef) {
, m_onclickRef(onclickRef)
, m_onenabledRef(onenabledRef)
{
}
~PluginCommand() {
@ -69,8 +72,30 @@ protected:
}
}
bool onEnabled(Context* context) override {
if (m_onenabledRef) {
script::Engine* engine = App::instance()->scriptEngine();
lua_State* L = engine->luaState();
lua_rawgeti(L, LUA_REGISTRYINDEX, m_onenabledRef);
if (lua_pcall(L, 0, 1, 0)) {
if (const char* s = lua_tostring(L, -1)) {
Console().printf("Error: %s", s);
return false;
}
}
else {
bool ret = lua_toboolean(L, -1);
lua_pop(L, 1);
return ret;
}
}
return true;
}
std::string m_title;
int m_onclickRef;
int m_onenabledRef;
};
void deleteCommandIfExistent(Extension* ext, const std::string& id)
@ -94,6 +119,7 @@ int Plugin_newCommand(lua_State* L)
auto plugin = get_obj<Plugin>(L, 1);
if (lua_istable(L, 2)) {
std::string id, title, group;
int onenabledRef = 0;
lua_getfield(L, 2, "id");
if (const char* s = lua_tostring(L, -1)) {
@ -116,7 +142,15 @@ int Plugin_newCommand(lua_State* L)
}
lua_pop(L, 1);
int type = lua_getfield(L, 2, "onclick");
int type = lua_getfield(L, 2, "onenabled");
if (type == LUA_TFUNCTION) {
onenabledRef = luaL_ref(L, LUA_REGISTRYINDEX); // does a pop
}
else {
lua_pop(L, 1);
}
type = lua_getfield(L, 2, "onclick");
if (type == LUA_TFUNCTION) {
int onclickRef = luaL_ref(L, LUA_REGISTRYINDEX);
@ -124,7 +158,7 @@ int Plugin_newCommand(lua_State* L)
// overwriting a previous registered command)
deleteCommandIfExistent(plugin->ext, id);
auto cmd = new PluginCommand(id, title, onclickRef);
auto cmd = new PluginCommand(id, title, onclickRef, onenabledRef);
Commands::instance()->add(cmd);
plugin->ext->addCommand(id);