df887f413ad34a256861a8034c1cc16b35bdc102
[oweals/minetest.git] / builtin / fstk / dialog.lua
1 --Minetest
2 --Copyright (C) 2014 sapier
3 --
4 --This program is free software; you can redistribute it and/or modify
5 --it under the terms of the GNU Lesser General Public License as published by
6 --the Free Software Foundation; either version 2.1 of the License, or
7 --(at your option) any later version.
8 --
9 --this program is distributed in the hope that it will be useful,
10 --but WITHOUT ANY WARRANTY; without even the implied warranty of
11 --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 --GNU Lesser General Public License for more details.
13 --
14 --You should have received a copy of the GNU Lesser General Public License along
15 --with this program; if not, write to the Free Software Foundation, Inc.,
16 --51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
18 local function dialog_event_handler(self,event)
19         if self.user_eventhandler == nil or
20                 self.user_eventhandler(event) == false then
21
22                 --close dialog on esc
23                 if event == "MenuQuit" then
24                         self:delete()
25                         return true
26                 end
27         end
28 end
29
30 local dialog_metatable = {
31         eventhandler = dialog_event_handler,
32         get_formspec = function(self)
33                                 if not self.hidden then return self.formspec(self.data) end
34                         end,
35         handle_buttons = function(self,fields)
36                                 if not self.hidden then return self.buttonhandler(self,fields) end
37                         end,
38         handle_events  = function(self,event)
39                                 if not self.hidden then return self.eventhandler(self,event) end
40                         end,
41         hide = function(self) self.hidden = true end,
42         show = function(self) self.hidden = false end,
43         delete = function(self)
44                         if self.parent ~= nil then
45                                 self.parent:show()
46                         end
47                         ui.delete(self)
48                 end,
49         set_parent = function(self,parent) self.parent = parent end
50 }
51 dialog_metatable.__index = dialog_metatable
52
53 function dialog_create(name,get_formspec,buttonhandler,eventhandler)
54         local self = {}
55
56         self.name = name
57         self.type = "toplevel"
58         self.hidden = true
59         self.data = {}
60
61         self.formspec      = get_formspec
62         self.buttonhandler = buttonhandler
63         self.user_eventhandler  = eventhandler
64
65         setmetatable(self,dialog_metatable)
66
67         ui.add(self)
68         return self
69 end