summaryrefslogtreecommitdiff
path: root/src/lua/lua_thread.cpp
blob: dc58814473567f9926efa2c44d90cd2546a5d048 (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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
/*
 * Copyright 2023 jacqueline <me@jacqueline.id.au>
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */

#include "lua_thread.hpp"

#include <memory>

#include "lua.hpp"

#include "font/lv_font_loader.h"
#include "luavgl.h"

#include "esp_heap_caps.h"
#include "esp_log.h"
#include "event_queue.hpp"
#include "service_locator.hpp"
#include "ui_events.hpp"

LV_FONT_DECLARE(font_fusion_12);
LV_FONT_DECLARE(font_fusion_10);

namespace lua {

[[maybe_unused]] static constexpr char kTag[] = "lua";

class Allocator {
 public:
  Allocator() : total_allocated_(0) {}

  auto alloc(void* ptr, size_t osize, size_t nsize) -> void* {
    total_allocated_ = total_allocated_ - osize + nsize;
    // ESP_LOGI(kTag, "lua realloc -> %u KiB", total_allocated_ / 1024);
    if (nsize == 0) {
      heap_caps_free(ptr);
      return NULL;
    } else {
      return heap_caps_realloc(ptr, nsize, MALLOC_CAP_SPIRAM);
    }
  }

 private:
  size_t total_allocated_;
};

static auto lua_alloc(void* ud, void* ptr, size_t osize, size_t nsize)
    -> void* {
  Allocator* instance = reinterpret_cast<Allocator*>(ud);
  return instance->alloc(ptr, osize, nsize);
}

static int lua_panic(lua_State* L) {
  ESP_LOGE(kTag, "!! PANIC !! %s", lua_tostring(L, -1));
  return 0;
}

static auto make_font_cb(const char* name, int size, int weight)
    -> const lv_font_t* {
  if (std::string{"fusion"} == name) {
    if (size == 12) {
      return &font_fusion_12;
    }
    if (size == 10) {
      return &font_fusion_10;
    }
  }
  return NULL;
}

static auto delete_font_cb(lv_font_t* font) -> void {}

auto LuaThread::Start(system_fsm::ServiceLocator& services, lv_obj_t* lvgl_root)
    -> LuaThread* {
  auto alloc = std::make_unique<Allocator>();
  lua_State* state = lua_newstate(lua_alloc, alloc.get());
  if (!state) {
    return nullptr;
  }

  luaL_openlibs(state);
  lua_atpanic(state, lua_panic);

  auto bridge = std::make_unique<Bridge>(services, *state);

  // FIXME: luavgl init should probably be a part of the bridge.
  if (lvgl_root) {
    luavgl_set_pcall(state, CallProtected);
    luavgl_set_font_extension(state, make_font_cb, delete_font_cb);
    luavgl_set_root(state, lvgl_root);
    luaL_requiref(state, "lvgl", luaopen_lvgl, true);
    lua_pop(state, 1);
  }

  return new LuaThread(alloc, bridge, state);
}

LuaThread::LuaThread(std::unique_ptr<Allocator>& alloc,
                     std::unique_ptr<Bridge>& bridge,
                     lua_State* state)
    : alloc_(std::move(alloc)), bridge_(std::move(bridge)), state_(state) {}

LuaThread::~LuaThread() {
  lua_close(state_);
}

auto LuaThread::RunScript(const std::string& path) -> bool {
  int res = luaL_loadfilex(state_, path.c_str(), NULL);
  if (res != LUA_OK) {
    return false;
  }
  CallProtected(state_, 0, 0);
  return true;
}

auto LuaThread::RunString(const std::string& script) -> bool {
  int res = luaL_loadstring(state_, script.c_str());
  if (res != LUA_OK) {
    return false;
  }
  CallProtected(state_, 0, 0);
  return true;
}

static int msg_handler(lua_State* L) {
  if (!lua_isstring(L, 1)) {
    return 1;
  }

  const char* msg = lua_tostring(L, 1);
  if (msg == NULL) {                         /* is error object not a string? */
    if (luaL_callmeta(L, 1, "__tostring") && /* does it have a metamethod */
        lua_type(L, -1) == LUA_TSTRING)      /* that produces a string? */
      return 1;                              /* that is the message */
    else
      msg = lua_pushfstring(L, "(error object is a %s value)",
                            luaL_typename(L, 1));
  }

  /* append a standard traceback */
  luaL_traceback(L, L, msg, 1);
  return 1;
}

auto CallProtected(lua_State* s, int nargs, int nresults) -> int {
  int base = lua_gettop(s) - nargs;
  // Place our message handler under the function to be called.
  lua_pushcfunction(s, msg_handler);
  lua_insert(s, base);

  // Invoke the function.
  int ret = lua_pcall(s, nargs, nresults, base);
  if (ret != LUA_OK) {
    events::Ui().Dispatch(ui::OnLuaError{.message = lua_tostring(s, -1)});
  }

  // Clean up our message handler
  lua_remove(s, base);

  return ret;
}

}  // namespace lua