summaryrefslogtreecommitdiff
path: root/src/ui/screen_lua.cpp
blob: d43c7ee785de93441e57d46e32f528904428f018 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
 * Copyright 2023 jacqueline <me@jacqueline.id.au>
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */

#include "screen_lua.hpp"

#include "core/lv_obj_tree.h"
#include "lua.h"
#include "lua.hpp"
#include "themes.hpp"

#include "lua_thread.hpp"
#include "luavgl.h"

namespace ui {
namespace screens {

Lua::Lua() : s_(nullptr), obj_ref_() {
  themes::Theme::instance()->ApplyStyle(root_, "root");
}

Lua::~Lua() {
  if (s_ && obj_ref_) {
    luaL_unref(s_, LUA_REGISTRYINDEX, *obj_ref_);
  }
}

auto Lua::onShown() -> void {
  if (!s_ || !obj_ref_) {
    return;
  }
  lua_rawgeti(s_, LUA_REGISTRYINDEX, *obj_ref_);
  lua_pushliteral(s_, "onShown");

  if (lua_gettable(s_, -2) == LUA_TFUNCTION) {
    lua_pushvalue(s_, -2);
    lua::CallProtected(s_, 1, 0);
  } else {
    lua_pop(s_, 1);
  }

  lua_pop(s_, 1);
}

auto Lua::onHidden() -> void {
  if (!s_ || !obj_ref_) {
    return;
  }
  lua_rawgeti(s_, LUA_REGISTRYINDEX, *obj_ref_);
  lua_pushliteral(s_, "onHidden");

  if (lua_gettable(s_, -2) == LUA_TFUNCTION) {
    lua_pushvalue(s_, -2);
    lua::CallProtected(s_, 1, 0);
  } else {
    lua_pop(s_, 1);
  }

  lua_pop(s_, 1);
}

auto Lua::canPop() -> bool {
  if (!s_ || !obj_ref_) {
    return true;
  }
  lua_rawgeti(s_, LUA_REGISTRYINDEX, *obj_ref_);
  lua_pushliteral(s_, "canPop");

  if (lua_gettable(s_, -2) == LUA_TFUNCTION) {
    // If we got a callback instead of a value, then invoke it to turn it into
    // value.
    lua_pushvalue(s_, -2);
    lua::CallProtected(s_, 1, 1);
  }
  bool ret = lua_toboolean(s_, -1);

  lua_pop(s_, 2);
  return ret;
}

auto Lua::SetObjRef(lua_State* s) -> void {
  assert(s_ == nullptr);
  s_ = s;
  obj_ref_ = luaL_ref(s, LUA_REGISTRYINDEX);
}

}  // namespace screens
}  // namespace ui