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