aboutsummaryrefslogtreecommitdiff
path: root/src/LuaRuntime.cpp
blob: e9a30b1c2c1c4b37df3e3230738e2b208583d5da (plain) (blame)
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
#include <QtCore>
#include <lua.hpp>
extern "C" {
#include <luv.h>
}

#include "AsyncEventLoop.hpp"
#include "LuaRuntime.hpp"

const char *uv_global_name = "uv";
const char *web_global_name = "web";

LuaRuntime::LuaRuntime() {
  state = luaL_newstate();
  luaL_openlibs(state);

  // Load `web`
  luaL_Reg weblib[] = {
      {"open", &LuaRuntime::lua_onUrlOpen},
      {"tabopen", &LuaRuntime::lua_onUrlTabOpen},
      {NULL, NULL},
  };
  luaL_newlib(state, weblib);
  lua_setglobal(state, web_global_name);
}

void LuaRuntime::startEventLoop() {
  if (eventLoop != nullptr)
    stopEventLoop();

  // Init event loop
  eventLoop = new AsyncEventLoop();

  // Load `uv` (luv)
  luv_set_loop(state, eventLoop->getUVLoop());
  luaopen_luv(state);
  lua_setglobal(state, uv_global_name);
}

void LuaRuntime::stopEventLoop() {
  if (eventLoop == nullptr)
    return;
  delete eventLoop;
  eventLoop = nullptr;

  // Clear the uv global
  lua_pushnil(state);
  lua_setglobal(state, uv_global_name);
  lua_gc(state, LUA_GCCOLLECT, 0);
}

void LuaRuntime::evaluate(QString code) {
  eventLoop->queueTask([this, code]() {
    if (luaL_dostring(state, code.toStdString().c_str())) {
      auto value = lua_tostring(state, -1);
      lua_pop(state, 1);

      qDebug() << "Lua Error: " << value;
      emit evaluationFailed(value);
    } else {
      auto value = getValue(-1);
      lua_pop(state, 1);

      qDebug() << "result: " << value;
      emit evaluationCompleted(value);
    }
  });
}

QVariant LuaRuntime::evaluateSync(QString code) {
  auto result = luaL_dostring(state, code.toStdString().c_str());
  return getValue(-1); // TODO: error handling
}

QVariant LuaRuntime::getValue(int idx) {
  if (lua_isstring(state, idx))
    return lua_tostring(state, idx);

  if (lua_isnumber(state, idx))
    return lua_tonumber(state, idx);

  if (lua_isboolean(state, idx))
    return lua_toboolean(state, idx);

  if (lua_isnil(state, idx))
    return 0; // TODO: nil representation

  return lua_tostring(state, idx);
}

int LuaRuntime::lua_onUrlOpen(lua_State *state) {
  const char *url = luaL_optstring(state, 1, "");
  auto runtime = LuaRuntime::instance();
  emit runtime->urlOpened(url, OpenType::OpenUrl);
  return 1;
}

int LuaRuntime::lua_onUrlTabOpen(lua_State *state) {
  const char *url = luaL_optstring(state, 1, "");
  auto runtime = LuaRuntime::instance();
  emit runtime->urlOpened(url, OpenType::OpenUrlInTab);
  return 1;
}

LuaRuntime::~LuaRuntime() {
  stopEventLoop();
  lua_close(state);
  state = nullptr;
}