summaryrefslogtreecommitdiff
path: root/plugins/MirLua/src/m_options.cpp
blob: f55af0f6d0ec4031214b54b63df095f13cda553e (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
#include "stdafx.h"

class CMLuaScriptOptionPage : public CDlgBase
{
private:
	int m_onInitDialogRef;
	int m_onApplyRef;
	lua_State *L;

public:
	CMLuaScriptOptionPage(lua_State *_L, int onInitDialogRef, int onApplyRef)
		: CDlgBase(g_hInstance, IDD_SCRIPTOPTIONSPAGE), L(_L),
		m_onInitDialogRef(onInitDialogRef), m_onApplyRef(onApplyRef)
	{
	}

	void OnInitDialog() override 
	{
		if (m_onInitDialogRef)
		{
			lua_rawgeti(L, LUA_REGISTRYINDEX, m_onInitDialogRef);
			lua_pushlightuserdata(L, m_hwnd);
			luaM_pcall(L, 1, 0);
		}
	}

	void OnApply() override
	{
		if (m_onApplyRef)
		{
			lua_rawgeti(L, LUA_REGISTRYINDEX, m_onApplyRef);
			lua_pushlightuserdata(L, m_hwnd);
			luaM_pcall(L, 1, 0);
		}
	}

	void OnDestroy() override
	{
		lua_pushnil(L);
		lua_rawsetp(L, LUA_REGISTRYINDEX, this);
	}
};

void MakeOptionDialogPage(lua_State *L, OPTIONSDIALOGPAGE &odp)
{
	odp.hInstance = g_hInstance;
	odp.hLangpack = CMLuaScript::GetScriptIdFromEnviroment(L);

	lua_getfield(L, -1, "Flags");
	odp.flags = luaL_optinteger(L, -1, ODPF_BOLDGROUPS | ODPF_UNICODE | ODPF_DONTTRANSLATE);
	lua_pop(L, 1);

	if (!(odp.flags & ODPF_UNICODE))
		odp.flags |= ODPF_UNICODE;

	lua_getfield(L, -1, "Group");
	odp.pwszGroup = mir_utf8decodeW(lua_tostring(L, -1));
	lua_pop(L, 1);

	lua_getfield(L, -1, "Title");
	odp.pwszTitle = mir_utf8decodeW(luaL_checkstring(L, -1));
	lua_pop(L, 1);

	lua_getfield(L, -1, "Tab");
	odp.pwszTab = mir_utf8decodeW(lua_tostring(L, -1));
	lua_pop(L, 1);

	int onInitDialogRef = LUA_NOREF;
	lua_getfield(L, -1, "OnInitDialog");
	if (lua_isfunction(L, -1))
		onInitDialogRef = luaL_ref(L, LUA_REGISTRYINDEX);
	else
		lua_pop(L, 1);

	int onApplyRef = LUA_NOREF;
	lua_getfield(L, -1, "OnApply");
	if (lua_isfunction(L, -1))
		onApplyRef = luaL_ref(L, LUA_REGISTRYINDEX);
	else
		lua_pop(L, 1);
	
	lua_State *T = lua_newthread(L);
	lua_rawsetp(L, LUA_REGISTRYINDEX, T);
	odp.pDialog = new CMLuaScriptOptionPage(T, onInitDialogRef, onApplyRef);
}

int opt_AddPage(lua_State *L)
{
	luaL_checktype(L, 1, LUA_TLIGHTUSERDATA);
	WPARAM wParam = (WPARAM)lua_touserdata(L, 1);

	OPTIONSDIALOGPAGE odp = { 0 };
	MakeOptionDialogPage(L, odp);

	INT_PTR res = Options_AddPage(wParam, &odp);
	lua_pushboolean(L, !res);

	mir_free(odp.pwszGroup);
	mir_free(odp.pwszTitle);
	mir_free(odp.pwszTab);

	return 1;
}

static luaL_Reg optionsApi[] =
{
	{ "AddPage", opt_AddPage },

	{ NULL, NULL }
};

LUAMOD_API int luaopen_m_options(lua_State *L)
{
	luaL_newlib(L, optionsApi);

	return 1;
}