summaryrefslogtreecommitdiff
path: root/src/cat/LuaTextbox.cpp
blob: e3a20ba0779ceb6a6aba7142a881a86116f4911e (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
extern "C"
{
#include "lua5.1/lua.h"
#include "lua5.1/lauxlib.h"
#include "lua5.1/lualib.h"
}

#include <iostream>
#include "LuaScriptInterface.h"
#include "LuaTextbox.h"
#include "interface/Textbox.h"

const char LuaTextbox::className[] = "Textbox";

#define method(class, name) {#name, &class::name}
Luna<LuaTextbox>::RegType LuaTextbox::methods[] = {
	method(LuaTextbox, text),
	method(LuaTextbox, readonly),
	method(LuaTextbox, onTextChanged),
	method(LuaTextbox, position),
	method(LuaTextbox, size),
	method(LuaTextbox, visible),
	{0, 0}
};

LuaTextbox::LuaTextbox(lua_State * l) :
	LuaComponent(l),
	onTextChangedFunction(0)
{
	this->l = l;
	int posX = luaL_optinteger(l, 1, 0);
	int posY = luaL_optinteger(l, 2, 0);
	int sizeX = luaL_optinteger(l, 3, 10);
	int sizeY = luaL_optinteger(l, 4, 10);
	std::string text = luaL_optstring(l, 5, "");
	std::string placeholder = luaL_optstring(l, 6, "");

	textbox = new ui::Textbox(ui::Point(posX, posY), ui::Point(sizeX, sizeY), text, placeholder);
	textbox->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
	class TextChangedAction : public ui::TextboxAction
	{
		LuaTextbox * t;
	public:
		TextChangedAction(LuaTextbox * t) : t(t) {}
		void TextChangedCallback(ui::Textbox * sender)
		{
			t->triggerOnTextChanged();
		}
	};
	textbox->SetActionCallback(new TextChangedAction(this));
	component = textbox;
}

int LuaTextbox::readonly(lua_State * l)
{
	int args = lua_gettop(l);
	if(args)
	{
		luaL_checktype(l, 1, LUA_TBOOLEAN);
		textbox->ReadOnly = lua_toboolean(l, 1);
		return 0;
	}
	else
	{
		lua_pushboolean(l, textbox->ReadOnly);
		return 1;
	}
}

int LuaTextbox::onTextChanged(lua_State * l)
{
	if(lua_type(l, 1) != LUA_TNIL)
	{
		luaL_checktype(l, 1, LUA_TFUNCTION);
		lua_pushvalue(l, 1);
		onTextChangedFunction = luaL_ref(l, LUA_REGISTRYINDEX);
	}
	else
	{
		onTextChangedFunction = 0;
	}
	return 0;
}

void LuaTextbox::triggerOnTextChanged()
{
	if(onTextChangedFunction)
	{
		lua_rawgeti(l, LUA_REGISTRYINDEX, onTextChangedFunction);
		lua_rawgeti(l, LUA_REGISTRYINDEX, UserData);
		if (lua_pcall(l, 1, 0, 0))
		{
			ci->Log(CommandInterface::LogError, lua_tostring(l, -1));
		}
	}
}

int LuaTextbox::text(lua_State * l)
{
	int args = lua_gettop(l);
	if(args)
	{
		luaL_checktype(l, 1, LUA_TSTRING);
		textbox->SetText(lua_tostring(l, 1));
		return 0;
	}
	else
	{
		lua_pushstring(l, textbox->GetText().c_str());
		return 1;
	}
}

LuaTextbox::~LuaTextbox()
{
}