Allow damage for attached objects, add attach/detach callbacks (#6786)
[oweals/minetest.git] / src / script / lua_api / l_mainmenu.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 sapier
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "lua_api/l_mainmenu.h"
21 #include "lua_api/l_internal.h"
22 #include "common/c_content.h"
23 #include "cpp_api/s_async.h"
24 #include "gui/guiEngine.h"
25 #include "gui/guiMainMenu.h"
26 #include "gui/guiKeyChangeMenu.h"
27 #include "gui/guiPathSelectMenu.h"
28 #include "version.h"
29 #include "porting.h"
30 #include "filesys.h"
31 #include "convert_json.h"
32 #include "content/packages.h"
33 #include "content/content.h"
34 #include "content/subgames.h"
35 #include "serverlist.h"
36 #include "mapgen/mapgen.h"
37 #include "settings.h"
38
39 #include <IFileArchive.h>
40 #include <IFileSystem.h>
41 #include "client/renderingengine.h"
42
43
44 /******************************************************************************/
45 std::string ModApiMainMenu::getTextData(lua_State *L, std::string name)
46 {
47         lua_getglobal(L, "gamedata");
48
49         lua_getfield(L, -1, name.c_str());
50
51         if(lua_isnil(L, -1))
52                 return "";
53
54         return luaL_checkstring(L, -1);
55 }
56
57 /******************************************************************************/
58 int ModApiMainMenu::getIntegerData(lua_State *L, std::string name,bool& valid)
59 {
60         lua_getglobal(L, "gamedata");
61
62         lua_getfield(L, -1, name.c_str());
63
64         if(lua_isnil(L, -1)) {
65                 valid = false;
66                 return -1;
67                 }
68
69         valid = true;
70         return luaL_checkinteger(L, -1);
71 }
72
73 /******************************************************************************/
74 int ModApiMainMenu::getBoolData(lua_State *L, std::string name,bool& valid)
75 {
76         lua_getglobal(L, "gamedata");
77
78         lua_getfield(L, -1, name.c_str());
79
80         if(lua_isnil(L, -1)) {
81                 valid = false;
82                 return false;
83                 }
84
85         valid = true;
86         return lua_toboolean(L, -1);
87 }
88
89 /******************************************************************************/
90 int ModApiMainMenu::l_update_formspec(lua_State *L)
91 {
92         GUIEngine* engine = getGuiEngine(L);
93         sanity_check(engine != NULL);
94
95         if (engine->m_startgame)
96                 return 0;
97
98         //read formspec
99         std::string formspec(luaL_checkstring(L, 1));
100
101         if (engine->m_formspecgui != 0) {
102                 engine->m_formspecgui->setForm(formspec);
103         }
104
105         return 0;
106 }
107
108 /******************************************************************************/
109 int ModApiMainMenu::l_start(lua_State *L)
110 {
111         GUIEngine* engine = getGuiEngine(L);
112         sanity_check(engine != NULL);
113
114         //update c++ gamedata from lua table
115
116         bool valid = false;
117
118         MainMenuData *data = engine->m_data;
119
120         data->selected_world = getIntegerData(L, "selected_world",valid) -1;
121         data->simple_singleplayer_mode = getBoolData(L,"singleplayer",valid);
122         data->do_reconnect = getBoolData(L, "do_reconnect", valid);
123         if (!data->do_reconnect) {
124                 data->name     = getTextData(L,"playername");
125                 data->password = getTextData(L,"password");
126                 data->address  = getTextData(L,"address");
127                 data->port     = getTextData(L,"port");
128         }
129         data->serverdescription = getTextData(L,"serverdescription");
130         data->servername        = getTextData(L,"servername");
131
132         //close menu next time
133         engine->m_startgame = true;
134         return 0;
135 }
136
137 /******************************************************************************/
138 int ModApiMainMenu::l_close(lua_State *L)
139 {
140         GUIEngine* engine = getGuiEngine(L);
141         sanity_check(engine != NULL);
142
143         engine->m_kill = true;
144         return 0;
145 }
146
147 /******************************************************************************/
148 int ModApiMainMenu::l_set_background(lua_State *L)
149 {
150         GUIEngine* engine = getGuiEngine(L);
151         sanity_check(engine != NULL);
152
153         std::string backgroundlevel(luaL_checkstring(L, 1));
154         std::string texturename(luaL_checkstring(L, 2));
155
156         bool tile_image = false;
157         bool retval     = false;
158         unsigned int minsize = 16;
159
160         if (!lua_isnone(L, 3)) {
161                 tile_image = lua_toboolean(L, 3);
162         }
163
164         if (!lua_isnone(L, 4)) {
165                 minsize = lua_tonumber(L, 4);
166         }
167
168         if (backgroundlevel == "background") {
169                 retval |= engine->setTexture(TEX_LAYER_BACKGROUND, texturename,
170                                 tile_image, minsize);
171         }
172
173         if (backgroundlevel == "overlay") {
174                 retval |= engine->setTexture(TEX_LAYER_OVERLAY, texturename,
175                                 tile_image, minsize);
176         }
177
178         if (backgroundlevel == "header") {
179                 retval |= engine->setTexture(TEX_LAYER_HEADER,  texturename,
180                                 tile_image, minsize);
181         }
182
183         if (backgroundlevel == "footer") {
184                 retval |= engine->setTexture(TEX_LAYER_FOOTER, texturename,
185                                 tile_image, minsize);
186         }
187
188         lua_pushboolean(L,retval);
189         return 1;
190 }
191
192 /******************************************************************************/
193 int ModApiMainMenu::l_set_clouds(lua_State *L)
194 {
195         GUIEngine* engine = getGuiEngine(L);
196         sanity_check(engine != NULL);
197
198         bool value = lua_toboolean(L,1);
199
200         engine->m_clouds_enabled = value;
201
202         return 0;
203 }
204
205 /******************************************************************************/
206 int ModApiMainMenu::l_get_textlist_index(lua_State *L)
207 {
208         // get_table_index accepts both tables and textlists
209         return l_get_table_index(L);
210 }
211
212 /******************************************************************************/
213 int ModApiMainMenu::l_get_table_index(lua_State *L)
214 {
215         GUIEngine* engine = getGuiEngine(L);
216         sanity_check(engine != NULL);
217
218         std::string tablename(luaL_checkstring(L, 1));
219         GUITable *table = engine->m_menu->getTable(tablename);
220         s32 selection = table ? table->getSelected() : 0;
221
222         if (selection >= 1)
223                 lua_pushinteger(L, selection);
224         else
225                 lua_pushnil(L);
226         return 1;
227 }
228
229 /******************************************************************************/
230 int ModApiMainMenu::l_get_worlds(lua_State *L)
231 {
232         std::vector<WorldSpec> worlds = getAvailableWorlds();
233
234         lua_newtable(L);
235         int top = lua_gettop(L);
236         unsigned int index = 1;
237
238         for (const WorldSpec &world : worlds) {
239                 lua_pushnumber(L,index);
240
241                 lua_newtable(L);
242                 int top_lvl2 = lua_gettop(L);
243
244                 lua_pushstring(L,"path");
245                 lua_pushstring(L, world.path.c_str());
246                 lua_settable(L, top_lvl2);
247
248                 lua_pushstring(L,"name");
249                 lua_pushstring(L, world.name.c_str());
250                 lua_settable(L, top_lvl2);
251
252                 lua_pushstring(L,"gameid");
253                 lua_pushstring(L, world.gameid.c_str());
254                 lua_settable(L, top_lvl2);
255
256                 lua_settable(L, top);
257                 index++;
258         }
259         return 1;
260 }
261
262 /******************************************************************************/
263 int ModApiMainMenu::l_get_favorites(lua_State *L)
264 {
265         std::string listtype = "local";
266
267         if (!lua_isnone(L,1)) {
268                 listtype = luaL_checkstring(L,1);
269         }
270
271         std::vector<ServerListSpec> servers;
272
273         if(listtype == "online") {
274                 servers = ServerList::getOnline();
275         } else {
276                 servers = ServerList::getLocal();
277         }
278
279         lua_newtable(L);
280         int top = lua_gettop(L);
281         unsigned int index = 1;
282
283         for (const Json::Value &server : servers) {
284
285                 lua_pushnumber(L,index);
286
287                 lua_newtable(L);
288                 int top_lvl2 = lua_gettop(L);
289
290                 if (!server["clients"].asString().empty()) {
291                         std::string clients_raw = server["clients"].asString();
292                         char* endptr = 0;
293                         int numbervalue = strtol(clients_raw.c_str(),&endptr,10);
294
295                         if ((!clients_raw.empty()) && (*endptr == 0)) {
296                                 lua_pushstring(L,"clients");
297                                 lua_pushnumber(L,numbervalue);
298                                 lua_settable(L, top_lvl2);
299                         }
300                 }
301
302                 if (!server["clients_max"].asString().empty()) {
303
304                         std::string clients_max_raw = server["clients_max"].asString();
305                         char* endptr = 0;
306                         int numbervalue = strtol(clients_max_raw.c_str(),&endptr,10);
307
308                         if ((!clients_max_raw.empty()) && (*endptr == 0)) {
309                                 lua_pushstring(L,"clients_max");
310                                 lua_pushnumber(L,numbervalue);
311                                 lua_settable(L, top_lvl2);
312                         }
313                 }
314
315                 if (!server["version"].asString().empty()) {
316                         lua_pushstring(L,"version");
317                         std::string topush = server["version"].asString();
318                         lua_pushstring(L,topush.c_str());
319                         lua_settable(L, top_lvl2);
320                 }
321
322                 if (!server["proto_min"].asString().empty()) {
323                         lua_pushstring(L,"proto_min");
324                         lua_pushinteger(L, server["proto_min"].asInt());
325                         lua_settable(L, top_lvl2);
326                 }
327
328                 if (!server["proto_max"].asString().empty()) {
329                         lua_pushstring(L,"proto_max");
330                         lua_pushinteger(L, server["proto_max"].asInt());
331                         lua_settable(L, top_lvl2);
332                 }
333
334                 if (!server["password"].asString().empty()) {
335                         lua_pushstring(L,"password");
336                         lua_pushboolean(L, server["password"].asBool());
337                         lua_settable(L, top_lvl2);
338                 }
339
340                 if (!server["creative"].asString().empty()) {
341                         lua_pushstring(L,"creative");
342                         lua_pushboolean(L, server["creative"].asBool());
343                         lua_settable(L, top_lvl2);
344                 }
345
346                 if (!server["damage"].asString().empty()) {
347                         lua_pushstring(L,"damage");
348                         lua_pushboolean(L, server["damage"].asBool());
349                         lua_settable(L, top_lvl2);
350                 }
351
352                 if (!server["pvp"].asString().empty()) {
353                         lua_pushstring(L,"pvp");
354                         lua_pushboolean(L, server["pvp"].asBool());
355                         lua_settable(L, top_lvl2);
356                 }
357
358                 if (!server["description"].asString().empty()) {
359                         lua_pushstring(L,"description");
360                         std::string topush = server["description"].asString();
361                         lua_pushstring(L,topush.c_str());
362                         lua_settable(L, top_lvl2);
363                 }
364
365                 if (!server["name"].asString().empty()) {
366                         lua_pushstring(L,"name");
367                         std::string topush = server["name"].asString();
368                         lua_pushstring(L,topush.c_str());
369                         lua_settable(L, top_lvl2);
370                 }
371
372                 if (!server["address"].asString().empty()) {
373                         lua_pushstring(L,"address");
374                         std::string topush = server["address"].asString();
375                         lua_pushstring(L,topush.c_str());
376                         lua_settable(L, top_lvl2);
377                 }
378
379                 if (!server["port"].asString().empty()) {
380                         lua_pushstring(L,"port");
381                         std::string topush = server["port"].asString();
382                         lua_pushstring(L,topush.c_str());
383                         lua_settable(L, top_lvl2);
384                 }
385
386                 if (server.isMember("ping")) {
387                         float ping = server["ping"].asFloat();
388                         lua_pushstring(L, "ping");
389                         lua_pushnumber(L, ping);
390                         lua_settable(L, top_lvl2);
391                 }
392
393                 lua_settable(L, top);
394                 index++;
395         }
396         return 1;
397 }
398
399 /******************************************************************************/
400 int ModApiMainMenu::l_delete_favorite(lua_State *L)
401 {
402         std::vector<ServerListSpec> servers;
403
404         std::string listtype = "local";
405
406         if (!lua_isnone(L,2)) {
407                 listtype = luaL_checkstring(L,2);
408         }
409
410         if ((listtype != "local") &&
411                 (listtype != "online"))
412                 return 0;
413
414
415         if(listtype == "online") {
416                 servers = ServerList::getOnline();
417         } else {
418                 servers = ServerList::getLocal();
419         }
420
421         int fav_idx     = luaL_checkinteger(L,1) -1;
422
423         if ((fav_idx >= 0) &&
424                         (fav_idx < (int) servers.size())) {
425
426                 ServerList::deleteEntry(servers[fav_idx]);
427         }
428
429         return 0;
430 }
431
432 /******************************************************************************/
433 int ModApiMainMenu::l_get_games(lua_State *L)
434 {
435         std::vector<SubgameSpec> games = getAvailableGames();
436
437         lua_newtable(L);
438         int top = lua_gettop(L);
439         unsigned int index = 1;
440
441         for (const SubgameSpec &game : games) {
442                 lua_pushnumber(L, index);
443                 lua_newtable(L);
444                 int top_lvl2 = lua_gettop(L);
445
446                 lua_pushstring(L, "id");
447                 lua_pushstring(L, game.id.c_str());
448                 lua_settable(L,   top_lvl2);
449
450                 lua_pushstring(L, "path");
451                 lua_pushstring(L, game.path.c_str());
452                 lua_settable(L,   top_lvl2);
453
454                 lua_pushstring(L, "type");
455                 lua_pushstring(L, "game");
456                 lua_settable(L,   top_lvl2);
457
458                 lua_pushstring(L, "gamemods_path");
459                 lua_pushstring(L, game.gamemods_path.c_str());
460                 lua_settable(L,   top_lvl2);
461
462                 lua_pushstring(L, "name");
463                 lua_pushstring(L, game.name.c_str());
464                 lua_settable(L,   top_lvl2);
465
466                 lua_pushstring(L, "author");
467                 lua_pushstring(L, game.author.c_str());
468                 lua_settable(L,   top_lvl2);
469
470                 lua_pushstring(L, "menuicon_path");
471                 lua_pushstring(L, game.menuicon_path.c_str());
472                 lua_settable(L,   top_lvl2);
473
474                 lua_pushstring(L, "addon_mods_paths");
475                 lua_newtable(L);
476                 int table2 = lua_gettop(L);
477                 int internal_index = 1;
478                 for (const std::string &addon_mods_path : game.addon_mods_paths) {
479                         lua_pushnumber(L, internal_index);
480                         lua_pushstring(L, addon_mods_path.c_str());
481                         lua_settable(L,   table2);
482                         internal_index++;
483                 }
484                 lua_settable(L, top_lvl2);
485                 lua_settable(L, top);
486                 index++;
487         }
488         return 1;
489 }
490
491 /******************************************************************************/
492 int ModApiMainMenu::l_get_content_info(lua_State *L)
493 {
494         std::string path = luaL_checkstring(L, 1);
495
496         ContentSpec spec;
497         spec.path = path;
498         parseContentInfo(spec);
499
500         lua_newtable(L);
501
502         lua_pushstring(L, spec.name.c_str());
503         lua_setfield(L, -2, "name");
504
505         lua_pushstring(L, spec.type.c_str());
506         lua_setfield(L, -2, "type");
507
508         lua_pushstring(L, spec.author.c_str());
509         lua_setfield(L, -2, "author");
510
511         lua_pushstring(L, spec.desc.c_str());
512         lua_setfield(L, -2, "description");
513
514         lua_pushstring(L, spec.path.c_str());
515         lua_setfield(L, -2, "path");
516
517         if (spec.type == "mod") {
518                 ModSpec spec;
519                 spec.path = path;
520                 parseModContents(spec);
521
522                 // Dependencies
523                 lua_newtable(L);
524                 int i = 1;
525                 for (const auto &dep : spec.depends) {
526                         lua_pushstring(L, dep.c_str());
527                         lua_rawseti(L, -2, i);
528                         i++;
529                 }
530                 lua_setfield(L, -2, "depends");
531
532                 // Optional Dependencies
533                 lua_newtable(L);
534                 i = 1;
535                 for (const auto &dep : spec.optdepends) {
536                         lua_pushstring(L, dep.c_str());
537                         lua_rawseti(L, -2, i);
538                         i++;
539                 }
540                 lua_setfield(L, -2, "optional_depends");
541         }
542
543         return 1;
544 }
545
546 /******************************************************************************/
547 int ModApiMainMenu::l_show_keys_menu(lua_State *L)
548 {
549         GUIEngine* engine = getGuiEngine(L);
550         sanity_check(engine != NULL);
551
552         GUIKeyChangeMenu *kmenu = new GUIKeyChangeMenu(RenderingEngine::get_gui_env(),
553                                                                 engine->m_parent,
554                                                                 -1,
555                                                                 engine->m_menumanager);
556         kmenu->drop();
557         return 0;
558 }
559
560 /******************************************************************************/
561 int ModApiMainMenu::l_create_world(lua_State *L)
562 {
563         const char *name        = luaL_checkstring(L, 1);
564         int gameidx                     = luaL_checkinteger(L,2) -1;
565
566         std::string path = porting::path_user + DIR_DELIM
567                         "worlds" + DIR_DELIM
568                         + name;
569
570         std::vector<SubgameSpec> games = getAvailableGames();
571
572         if ((gameidx >= 0) &&
573                         (gameidx < (int) games.size())) {
574
575                 // Create world if it doesn't exist
576                 if (!loadGameConfAndInitWorld(path, games[gameidx])) {
577                         lua_pushstring(L, "Failed to initialize world");
578                 } else {
579                         lua_pushnil(L);
580                 }
581         } else {
582                 lua_pushstring(L, "Invalid game index");
583         }
584         return 1;
585 }
586
587 /******************************************************************************/
588 int ModApiMainMenu::l_delete_world(lua_State *L)
589 {
590         int worldidx    = luaL_checkinteger(L,1) -1;
591
592         std::vector<WorldSpec> worlds = getAvailableWorlds();
593
594         if ((worldidx >= 0) &&
595                 (worldidx < (int) worlds.size())) {
596
597                 WorldSpec spec = worlds[worldidx];
598
599                 std::vector<std::string> paths;
600                 paths.push_back(spec.path);
601                 fs::GetRecursiveSubPaths(spec.path, paths, true);
602
603                 // Delete files
604                 if (!fs::DeletePaths(paths)) {
605                         lua_pushstring(L, "Failed to delete world");
606                 }
607                 else {
608                         lua_pushnil(L);
609                 }
610         }
611         else {
612                 lua_pushstring(L, "Invalid world index");
613         }
614         return 1;
615 }
616
617 /******************************************************************************/
618 int ModApiMainMenu::l_set_topleft_text(lua_State *L)
619 {
620         GUIEngine* engine = getGuiEngine(L);
621         sanity_check(engine != NULL);
622
623         std::string text;
624
625         if (!lua_isnone(L,1) && !lua_isnil(L,1))
626                 text = luaL_checkstring(L, 1);
627
628         engine->setTopleftText(text);
629         return 0;
630 }
631
632 /******************************************************************************/
633 int ModApiMainMenu::l_get_mapgen_names(lua_State *L)
634 {
635         std::vector<const char *> names;
636         Mapgen::getMapgenNames(&names, lua_toboolean(L, 1));
637
638         lua_newtable(L);
639         for (size_t i = 0; i != names.size(); i++) {
640                 lua_pushstring(L, names[i]);
641                 lua_rawseti(L, -2, i + 1);
642         }
643
644         return 1;
645 }
646
647
648 /******************************************************************************/
649 int ModApiMainMenu::l_get_modpath(lua_State *L)
650 {
651         std::string modpath = fs::RemoveRelativePathComponents(
652                 porting::path_user + DIR_DELIM + "mods" + DIR_DELIM);
653         lua_pushstring(L, modpath.c_str());
654         return 1;
655 }
656
657 /******************************************************************************/
658 int ModApiMainMenu::l_get_clientmodpath(lua_State *L)
659 {
660         std::string modpath = fs::RemoveRelativePathComponents(
661                 porting::path_user + DIR_DELIM + "clientmods" + DIR_DELIM);
662         lua_pushstring(L, modpath.c_str());
663         return 1;
664 }
665
666 /******************************************************************************/
667 int ModApiMainMenu::l_get_gamepath(lua_State *L)
668 {
669         std::string gamepath = fs::RemoveRelativePathComponents(
670                 porting::path_user + DIR_DELIM + "games" + DIR_DELIM);
671         lua_pushstring(L, gamepath.c_str());
672         return 1;
673 }
674
675 /******************************************************************************/
676 int ModApiMainMenu::l_get_texturepath(lua_State *L)
677 {
678         std::string gamepath = fs::RemoveRelativePathComponents(
679                 porting::path_user + DIR_DELIM + "textures");
680         lua_pushstring(L, gamepath.c_str());
681         return 1;
682 }
683
684 int ModApiMainMenu::l_get_texturepath_share(lua_State *L)
685 {
686         std::string gamepath = fs::RemoveRelativePathComponents(
687                 porting::path_share + DIR_DELIM + "textures");
688         lua_pushstring(L, gamepath.c_str());
689         return 1;
690 }
691
692 /******************************************************************************/
693 int ModApiMainMenu::l_create_dir(lua_State *L) {
694         const char *path = luaL_checkstring(L, 1);
695
696         if (ModApiMainMenu::isMinetestPath(path)) {
697                 lua_pushboolean(L, fs::CreateAllDirs(path));
698                 return 1;
699         }
700
701         lua_pushboolean(L, false);
702         return 1;
703 }
704
705 /******************************************************************************/
706 int ModApiMainMenu::l_delete_dir(lua_State *L)
707 {
708         const char *path = luaL_checkstring(L, 1);
709
710         std::string absolute_path = fs::RemoveRelativePathComponents(path);
711
712         if (ModApiMainMenu::isMinetestPath(absolute_path)) {
713                 lua_pushboolean(L, fs::RecursiveDelete(absolute_path));
714                 return 1;
715         }
716
717         lua_pushboolean(L, false);
718         return 1;
719 }
720
721 /******************************************************************************/
722 int ModApiMainMenu::l_copy_dir(lua_State *L)
723 {
724         const char *source      = luaL_checkstring(L, 1);
725         const char *destination = luaL_checkstring(L, 2);
726
727         bool keep_source = true;
728
729         if ((!lua_isnone(L,3)) &&
730                         (!lua_isnil(L,3))) {
731                 keep_source = lua_toboolean(L,3);
732         }
733
734         std::string absolute_destination = fs::RemoveRelativePathComponents(destination);
735         std::string absolute_source = fs::RemoveRelativePathComponents(source);
736
737         if ((ModApiMainMenu::isMinetestPath(absolute_destination))) {
738                 bool retval = fs::CopyDir(absolute_source,absolute_destination);
739
740                 if (retval && (!keep_source)) {
741
742                         retval &= fs::RecursiveDelete(absolute_source);
743                 }
744                 lua_pushboolean(L,retval);
745                 return 1;
746         }
747         lua_pushboolean(L,false);
748         return 1;
749 }
750
751 /******************************************************************************/
752 int ModApiMainMenu::l_extract_zip(lua_State *L)
753 {
754         const char *zipfile     = luaL_checkstring(L, 1);
755         const char *destination = luaL_checkstring(L, 2);
756
757         std::string absolute_destination = fs::RemoveRelativePathComponents(destination);
758
759         if (ModApiMainMenu::isMinetestPath(absolute_destination)) {
760                 fs::CreateAllDirs(absolute_destination);
761
762                 io::IFileSystem *fs = RenderingEngine::get_filesystem();
763
764                 if (!fs->addFileArchive(zipfile,true,false,io::EFAT_ZIP)) {
765                         lua_pushboolean(L,false);
766                         return 1;
767                 }
768
769                 sanity_check(fs->getFileArchiveCount() > 0);
770
771                 /**********************************************************************/
772                 /* WARNING this is not threadsafe!!                                   */
773                 /**********************************************************************/
774                 io::IFileArchive* opened_zip =
775                         fs->getFileArchive(fs->getFileArchiveCount()-1);
776
777                 const io::IFileList* files_in_zip = opened_zip->getFileList();
778
779                 unsigned int number_of_files = files_in_zip->getFileCount();
780
781                 for (unsigned int i=0; i < number_of_files; i++) {
782                         std::string fullpath = destination;
783                         fullpath += DIR_DELIM;
784                         fullpath += files_in_zip->getFullFileName(i).c_str();
785                         std::string fullpath_dir = fs::RemoveLastPathComponent(fullpath);
786
787                         if (!files_in_zip->isDirectory(i)) {
788                                 if (!fs::PathExists(fullpath_dir) && !fs::CreateAllDirs(fullpath_dir)) {
789                                         fs->removeFileArchive(fs->getFileArchiveCount()-1);
790                                         lua_pushboolean(L,false);
791                                         return 1;
792                                 }
793
794                                 io::IReadFile* toread = opened_zip->createAndOpenFile(i);
795
796                                 FILE *targetfile = fopen(fullpath.c_str(),"wb");
797
798                                 if (targetfile == NULL) {
799                                         fs->removeFileArchive(fs->getFileArchiveCount()-1);
800                                         lua_pushboolean(L,false);
801                                         return 1;
802                                 }
803
804                                 char read_buffer[1024];
805                                 long total_read = 0;
806
807                                 while (total_read < toread->getSize()) {
808
809                                         unsigned int bytes_read =
810                                                         toread->read(read_buffer,sizeof(read_buffer));
811                                         if ((bytes_read == 0 ) ||
812                                                 (fwrite(read_buffer, 1, bytes_read, targetfile) != bytes_read))
813                                         {
814                                                 fclose(targetfile);
815                                                 fs->removeFileArchive(fs->getFileArchiveCount()-1);
816                                                 lua_pushboolean(L,false);
817                                                 return 1;
818                                         }
819                                         total_read += bytes_read;
820                                 }
821
822                                 fclose(targetfile);
823                         }
824
825                 }
826
827                 fs->removeFileArchive(fs->getFileArchiveCount()-1);
828                 lua_pushboolean(L,true);
829                 return 1;
830         }
831
832         lua_pushboolean(L,false);
833         return 1;
834 }
835
836 /******************************************************************************/
837 int ModApiMainMenu::l_get_mainmenu_path(lua_State *L)
838 {
839         GUIEngine* engine = getGuiEngine(L);
840         sanity_check(engine != NULL);
841
842         lua_pushstring(L,engine->getScriptDir().c_str());
843         return 1;
844 }
845
846 /******************************************************************************/
847 bool ModApiMainMenu::isMinetestPath(std::string path)
848 {
849         if (fs::PathStartsWith(path,fs::TempPath()))
850                 return true;
851
852         /* games */
853         if (fs::PathStartsWith(path,fs::RemoveRelativePathComponents(porting::path_share + DIR_DELIM + "games")))
854                 return true;
855
856         /* mods */
857         if (fs::PathStartsWith(path,fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM + "mods")))
858                 return true;
859
860         /* mods */
861         if (fs::PathStartsWith(path,fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM + "textures")))
862                 return true;
863
864         /* worlds */
865         if (fs::PathStartsWith(path,fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM + "worlds")))
866                 return true;
867
868
869         return false;
870 }
871
872 /******************************************************************************/
873 int ModApiMainMenu::l_show_path_select_dialog(lua_State *L)
874 {
875         GUIEngine* engine = getGuiEngine(L);
876         sanity_check(engine != NULL);
877
878         const char *formname= luaL_checkstring(L, 1);
879         const char *title       = luaL_checkstring(L, 2);
880         bool is_file_select = lua_toboolean(L, 3);
881
882         GUIFileSelectMenu* fileOpenMenu =
883                 new GUIFileSelectMenu(RenderingEngine::get_gui_env(),
884                                                                 engine->m_parent,
885                                                                 -1,
886                                                                 engine->m_menumanager,
887                                                                 title,
888                                                                 formname,
889                                                                 is_file_select);
890         fileOpenMenu->setTextDest(engine->m_buttonhandler);
891         fileOpenMenu->drop();
892         return 0;
893 }
894
895 /******************************************************************************/
896 int ModApiMainMenu::l_download_file(lua_State *L)
897 {
898         const char *url    = luaL_checkstring(L, 1);
899         const char *target = luaL_checkstring(L, 2);
900
901         //check path
902         std::string absolute_destination = fs::RemoveRelativePathComponents(target);
903
904         if (ModApiMainMenu::isMinetestPath(absolute_destination)) {
905                 if (GUIEngine::downloadFile(url,absolute_destination)) {
906                         lua_pushboolean(L,true);
907                         return 1;
908                 }
909         } else {
910                 errorstream << "DOWNLOAD denied: " << absolute_destination
911                                 << " isn't a allowed path" << std::endl;
912         }
913         lua_pushboolean(L,false);
914         return 1;
915 }
916
917 /******************************************************************************/
918 int ModApiMainMenu::l_get_video_drivers(lua_State *L)
919 {
920         std::vector<irr::video::E_DRIVER_TYPE> drivers = RenderingEngine::getSupportedVideoDrivers();
921
922         lua_newtable(L);
923         for (u32 i = 0; i != drivers.size(); i++) {
924                 const char *name  = RenderingEngine::getVideoDriverName(drivers[i]);
925                 const char *fname = RenderingEngine::getVideoDriverFriendlyName(drivers[i]);
926
927                 lua_newtable(L);
928                 lua_pushstring(L, name);
929                 lua_setfield(L, -2, "name");
930                 lua_pushstring(L, fname);
931                 lua_setfield(L, -2, "friendly_name");
932
933                 lua_rawseti(L, -2, i + 1);
934         }
935
936         return 1;
937 }
938
939 /******************************************************************************/
940 int ModApiMainMenu::l_get_video_modes(lua_State *L)
941 {
942         std::vector<core::vector3d<u32> > videomodes
943                 = RenderingEngine::getSupportedVideoModes();
944
945         lua_newtable(L);
946         for (u32 i = 0; i != videomodes.size(); i++) {
947                 lua_newtable(L);
948                 lua_pushnumber(L, videomodes[i].X);
949                 lua_setfield(L, -2, "w");
950                 lua_pushnumber(L, videomodes[i].Y);
951                 lua_setfield(L, -2, "h");
952                 lua_pushnumber(L, videomodes[i].Z);
953                 lua_setfield(L, -2, "depth");
954
955                 lua_rawseti(L, -2, i + 1);
956         }
957
958         return 1;
959 }
960
961 /******************************************************************************/
962 int ModApiMainMenu::l_gettext(lua_State *L)
963 {
964         std::string text = strgettext(std::string(luaL_checkstring(L, 1)));
965         lua_pushstring(L, text.c_str());
966
967         return 1;
968 }
969
970 /******************************************************************************/
971 int ModApiMainMenu::l_get_screen_info(lua_State *L)
972 {
973         lua_newtable(L);
974         int top = lua_gettop(L);
975         lua_pushstring(L,"density");
976         lua_pushnumber(L,RenderingEngine::getDisplayDensity());
977         lua_settable(L, top);
978
979         lua_pushstring(L,"display_width");
980         lua_pushnumber(L,RenderingEngine::getDisplaySize().X);
981         lua_settable(L, top);
982
983         lua_pushstring(L,"display_height");
984         lua_pushnumber(L,RenderingEngine::getDisplaySize().Y);
985         lua_settable(L, top);
986
987         const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize();
988         lua_pushstring(L,"window_width");
989         lua_pushnumber(L, window_size.X);
990         lua_settable(L, top);
991
992         lua_pushstring(L,"window_height");
993         lua_pushnumber(L, window_size.Y);
994         lua_settable(L, top);
995         return 1;
996 }
997
998 int ModApiMainMenu::l_get_package_list(lua_State *L)
999 {
1000         std::string url = g_settings->get("contentdb_url");
1001         std::vector<Package> packages = getPackagesFromURL(url + "/packages/");
1002
1003         // Make table
1004         lua_newtable(L);
1005         int top = lua_gettop(L);
1006         unsigned int index = 1;
1007
1008         // Fill table
1009         for (const auto &package : packages) {
1010                 lua_pushnumber(L, index);
1011                 lua_newtable(L);
1012
1013                 int top_lvl2 = lua_gettop(L);
1014
1015                 lua_pushstring(L, "name");
1016                 lua_pushstring(L, package.name.c_str());
1017                 lua_settable  (L, top_lvl2);
1018
1019                 lua_pushstring(L, "title");
1020                 lua_pushstring(L, package.title.c_str());
1021                 lua_settable  (L, top_lvl2);
1022
1023                 lua_pushstring(L, "author");
1024                 lua_pushstring(L, package.author.c_str());
1025                 lua_settable  (L, top_lvl2);
1026
1027                 lua_pushstring(L, "type");
1028                 lua_pushstring(L, package.type.c_str());
1029                 lua_settable  (L, top_lvl2);
1030
1031                 lua_pushstring(L, "short_description");
1032                 lua_pushstring(L, package.shortDesc.c_str());
1033                 lua_settable  (L, top_lvl2);
1034
1035                 lua_pushstring(L, "url");
1036                 lua_pushstring(L, package.url.c_str());
1037                 lua_settable  (L, top_lvl2);
1038
1039                 lua_settable(L, top);
1040                 index++;
1041         }
1042
1043         return 1;
1044 }
1045
1046 /******************************************************************************/
1047 int ModApiMainMenu::l_get_min_supp_proto(lua_State *L)
1048 {
1049         lua_pushinteger(L, CLIENT_PROTOCOL_VERSION_MIN);
1050         return 1;
1051 }
1052
1053 int ModApiMainMenu::l_get_max_supp_proto(lua_State *L)
1054 {
1055         lua_pushinteger(L, CLIENT_PROTOCOL_VERSION_MAX);
1056         return 1;
1057 }
1058
1059 /******************************************************************************/
1060 int ModApiMainMenu::l_do_async_callback(lua_State *L)
1061 {
1062         GUIEngine* engine = getGuiEngine(L);
1063
1064         size_t func_length, param_length;
1065         const char* serialized_func_raw = luaL_checklstring(L, 1, &func_length);
1066
1067         const char* serialized_param_raw = luaL_checklstring(L, 2, &param_length);
1068
1069         sanity_check(serialized_func_raw != NULL);
1070         sanity_check(serialized_param_raw != NULL);
1071
1072         std::string serialized_func = std::string(serialized_func_raw, func_length);
1073         std::string serialized_param = std::string(serialized_param_raw, param_length);
1074
1075         lua_pushinteger(L, engine->queueAsync(serialized_func, serialized_param));
1076
1077         return 1;
1078 }
1079
1080 /******************************************************************************/
1081 void ModApiMainMenu::Initialize(lua_State *L, int top)
1082 {
1083         API_FCT(update_formspec);
1084         API_FCT(set_clouds);
1085         API_FCT(get_textlist_index);
1086         API_FCT(get_table_index);
1087         API_FCT(get_worlds);
1088         API_FCT(get_games);
1089         API_FCT(get_content_info);
1090         API_FCT(start);
1091         API_FCT(close);
1092         API_FCT(get_favorites);
1093         API_FCT(show_keys_menu);
1094         API_FCT(create_world);
1095         API_FCT(delete_world);
1096         API_FCT(delete_favorite);
1097         API_FCT(set_background);
1098         API_FCT(set_topleft_text);
1099         API_FCT(get_mapgen_names);
1100         API_FCT(get_modpath);
1101         API_FCT(get_clientmodpath);
1102         API_FCT(get_gamepath);
1103         API_FCT(get_texturepath);
1104         API_FCT(get_texturepath_share);
1105         API_FCT(create_dir);
1106         API_FCT(delete_dir);
1107         API_FCT(copy_dir);
1108         API_FCT(extract_zip);
1109         API_FCT(get_mainmenu_path);
1110         API_FCT(show_path_select_dialog);
1111         API_FCT(download_file);
1112         API_FCT(gettext);
1113         API_FCT(get_video_drivers);
1114         API_FCT(get_video_modes);
1115         API_FCT(get_screen_info);
1116         API_FCT(get_package_list);
1117         API_FCT(get_min_supp_proto);
1118         API_FCT(get_max_supp_proto);
1119         API_FCT(do_async_callback);
1120 }
1121
1122 /******************************************************************************/
1123 void ModApiMainMenu::InitializeAsync(lua_State *L, int top)
1124 {
1125         API_FCT(get_worlds);
1126         API_FCT(get_games);
1127         API_FCT(get_favorites);
1128         API_FCT(get_mapgen_names);
1129         API_FCT(get_modpath);
1130         API_FCT(get_clientmodpath);
1131         API_FCT(get_gamepath);
1132         API_FCT(get_texturepath);
1133         API_FCT(get_texturepath_share);
1134         API_FCT(create_dir);
1135         API_FCT(delete_dir);
1136         API_FCT(copy_dir);
1137         //API_FCT(extract_zip); //TODO remove dependency to GuiEngine
1138         API_FCT(download_file);
1139         //API_FCT(gettext); (gettext lib isn't threadsafe)
1140         API_FCT(get_package_list);
1141 }