Modernize lua read (part 2 & 3): C++ templating assurance (#7410)
[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 readParam<bool>(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 = readParam<bool>(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 = readParam<bool>(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,  "release");
471                 lua_pushinteger(L, game.release);
472                 lua_settable(L,    top_lvl2);
473
474                 lua_pushstring(L,  "menuicon_path");
475                 lua_pushstring(L,  game.menuicon_path.c_str());
476                 lua_settable(L,    top_lvl2);
477
478                 lua_pushstring(L, "addon_mods_paths");
479                 lua_newtable(L);
480                 int table2 = lua_gettop(L);
481                 int internal_index = 1;
482                 for (const std::string &addon_mods_path : game.addon_mods_paths) {
483                         lua_pushnumber(L, internal_index);
484                         lua_pushstring(L, addon_mods_path.c_str());
485                         lua_settable(L,   table2);
486                         internal_index++;
487                 }
488                 lua_settable(L, top_lvl2);
489                 lua_settable(L, top);
490                 index++;
491         }
492         return 1;
493 }
494
495 /******************************************************************************/
496 int ModApiMainMenu::l_get_content_info(lua_State *L)
497 {
498         std::string path = luaL_checkstring(L, 1);
499
500         ContentSpec spec;
501         spec.path = path;
502         parseContentInfo(spec);
503
504         lua_newtable(L);
505
506         lua_pushstring(L, spec.name.c_str());
507         lua_setfield(L, -2, "name");
508
509         lua_pushstring(L, spec.type.c_str());
510         lua_setfield(L, -2, "type");
511
512         lua_pushstring(L, spec.author.c_str());
513         lua_setfield(L, -2, "author");
514
515         lua_pushinteger(L, spec.release);
516         lua_setfield(L, -2, "release");
517
518         lua_pushstring(L, spec.desc.c_str());
519         lua_setfield(L, -2, "description");
520
521         lua_pushstring(L, spec.path.c_str());
522         lua_setfield(L, -2, "path");
523
524         if (spec.type == "mod") {
525                 ModSpec spec;
526                 spec.path = path;
527                 parseModContents(spec);
528
529                 // Dependencies
530                 lua_newtable(L);
531                 int i = 1;
532                 for (const auto &dep : spec.depends) {
533                         lua_pushstring(L, dep.c_str());
534                         lua_rawseti(L, -2, i);
535                         i++;
536                 }
537                 lua_setfield(L, -2, "depends");
538
539                 // Optional Dependencies
540                 lua_newtable(L);
541                 i = 1;
542                 for (const auto &dep : spec.optdepends) {
543                         lua_pushstring(L, dep.c_str());
544                         lua_rawseti(L, -2, i);
545                         i++;
546                 }
547                 lua_setfield(L, -2, "optional_depends");
548         }
549
550         return 1;
551 }
552
553 /******************************************************************************/
554 int ModApiMainMenu::l_show_keys_menu(lua_State *L)
555 {
556         GUIEngine* engine = getGuiEngine(L);
557         sanity_check(engine != NULL);
558
559         GUIKeyChangeMenu *kmenu = new GUIKeyChangeMenu(RenderingEngine::get_gui_env(),
560                                                                 engine->m_parent,
561                                                                 -1,
562                                                                 engine->m_menumanager);
563         kmenu->drop();
564         return 0;
565 }
566
567 /******************************************************************************/
568 int ModApiMainMenu::l_create_world(lua_State *L)
569 {
570         const char *name        = luaL_checkstring(L, 1);
571         int gameidx                     = luaL_checkinteger(L,2) -1;
572
573         std::string path = porting::path_user + DIR_DELIM
574                         "worlds" + DIR_DELIM
575                         + name;
576
577         std::vector<SubgameSpec> games = getAvailableGames();
578
579         if ((gameidx >= 0) &&
580                         (gameidx < (int) games.size())) {
581
582                 // Create world if it doesn't exist
583                 if (!loadGameConfAndInitWorld(path, games[gameidx])) {
584                         lua_pushstring(L, "Failed to initialize world");
585                 } else {
586                         lua_pushnil(L);
587                 }
588         } else {
589                 lua_pushstring(L, "Invalid game index");
590         }
591         return 1;
592 }
593
594 /******************************************************************************/
595 int ModApiMainMenu::l_delete_world(lua_State *L)
596 {
597         int world_id = luaL_checkinteger(L, 1) - 1;
598         std::vector<WorldSpec> worlds = getAvailableWorlds();
599         if (world_id < 0 || world_id >= (int) worlds.size()) {
600                 lua_pushstring(L, "Invalid world index");
601                 return 1;
602         }
603         const WorldSpec &spec = worlds[world_id];
604         if (!fs::RecursiveDelete(spec.path)) {
605                 lua_pushstring(L, "Failed to delete world");
606                 return 1;
607         }
608         return 0;
609 }
610
611 /******************************************************************************/
612 int ModApiMainMenu::l_set_topleft_text(lua_State *L)
613 {
614         GUIEngine* engine = getGuiEngine(L);
615         sanity_check(engine != NULL);
616
617         std::string text;
618
619         if (!lua_isnone(L,1) && !lua_isnil(L,1))
620                 text = luaL_checkstring(L, 1);
621
622         engine->setTopleftText(text);
623         return 0;
624 }
625
626 /******************************************************************************/
627 int ModApiMainMenu::l_get_mapgen_names(lua_State *L)
628 {
629         std::vector<const char *> names;
630         bool include_hidden = lua_isboolean(L, 1) && readParam<bool>(L, 1);
631         Mapgen::getMapgenNames(&names, include_hidden);
632
633         lua_newtable(L);
634         for (size_t i = 0; i != names.size(); i++) {
635                 lua_pushstring(L, names[i]);
636                 lua_rawseti(L, -2, i + 1);
637         }
638
639         return 1;
640 }
641
642
643 /******************************************************************************/
644 int ModApiMainMenu::l_get_modpath(lua_State *L)
645 {
646         std::string modpath = fs::RemoveRelativePathComponents(
647                 porting::path_user + DIR_DELIM + "mods" + DIR_DELIM);
648         lua_pushstring(L, modpath.c_str());
649         return 1;
650 }
651
652 /******************************************************************************/
653 int ModApiMainMenu::l_get_clientmodpath(lua_State *L)
654 {
655         std::string modpath = fs::RemoveRelativePathComponents(
656                 porting::path_user + DIR_DELIM + "clientmods" + DIR_DELIM);
657         lua_pushstring(L, modpath.c_str());
658         return 1;
659 }
660
661 /******************************************************************************/
662 int ModApiMainMenu::l_get_gamepath(lua_State *L)
663 {
664         std::string gamepath = fs::RemoveRelativePathComponents(
665                 porting::path_user + DIR_DELIM + "games" + DIR_DELIM);
666         lua_pushstring(L, gamepath.c_str());
667         return 1;
668 }
669
670 /******************************************************************************/
671 int ModApiMainMenu::l_get_texturepath(lua_State *L)
672 {
673         std::string gamepath = fs::RemoveRelativePathComponents(
674                 porting::path_user + DIR_DELIM + "textures");
675         lua_pushstring(L, gamepath.c_str());
676         return 1;
677 }
678
679 int ModApiMainMenu::l_get_texturepath_share(lua_State *L)
680 {
681         std::string gamepath = fs::RemoveRelativePathComponents(
682                 porting::path_share + DIR_DELIM + "textures");
683         lua_pushstring(L, gamepath.c_str());
684         return 1;
685 }
686
687 /******************************************************************************/
688 int ModApiMainMenu::l_create_dir(lua_State *L) {
689         const char *path = luaL_checkstring(L, 1);
690
691         if (ModApiMainMenu::isMinetestPath(path)) {
692                 lua_pushboolean(L, fs::CreateAllDirs(path));
693                 return 1;
694         }
695
696         lua_pushboolean(L, false);
697         return 1;
698 }
699
700 /******************************************************************************/
701 int ModApiMainMenu::l_delete_dir(lua_State *L)
702 {
703         const char *path = luaL_checkstring(L, 1);
704
705         std::string absolute_path = fs::RemoveRelativePathComponents(path);
706
707         if (ModApiMainMenu::isMinetestPath(absolute_path)) {
708                 lua_pushboolean(L, fs::RecursiveDelete(absolute_path));
709                 return 1;
710         }
711
712         lua_pushboolean(L, false);
713         return 1;
714 }
715
716 /******************************************************************************/
717 int ModApiMainMenu::l_copy_dir(lua_State *L)
718 {
719         const char *source      = luaL_checkstring(L, 1);
720         const char *destination = luaL_checkstring(L, 2);
721
722         bool keep_source = true;
723
724         if ((!lua_isnone(L,3)) &&
725                         (!lua_isnil(L,3))) {
726                 keep_source = readParam<bool>(L,3);
727         }
728
729         std::string absolute_destination = fs::RemoveRelativePathComponents(destination);
730         std::string absolute_source = fs::RemoveRelativePathComponents(source);
731
732         if ((ModApiMainMenu::isMinetestPath(absolute_destination))) {
733                 bool retval = fs::CopyDir(absolute_source,absolute_destination);
734
735                 if (retval && (!keep_source)) {
736
737                         retval &= fs::RecursiveDelete(absolute_source);
738                 }
739                 lua_pushboolean(L,retval);
740                 return 1;
741         }
742         lua_pushboolean(L,false);
743         return 1;
744 }
745
746 /******************************************************************************/
747 int ModApiMainMenu::l_extract_zip(lua_State *L)
748 {
749         const char *zipfile     = luaL_checkstring(L, 1);
750         const char *destination = luaL_checkstring(L, 2);
751
752         std::string absolute_destination = fs::RemoveRelativePathComponents(destination);
753
754         if (ModApiMainMenu::isMinetestPath(absolute_destination)) {
755                 fs::CreateAllDirs(absolute_destination);
756
757                 io::IFileSystem *fs = RenderingEngine::get_filesystem();
758
759                 if (!fs->addFileArchive(zipfile,true,false,io::EFAT_ZIP)) {
760                         lua_pushboolean(L,false);
761                         return 1;
762                 }
763
764                 sanity_check(fs->getFileArchiveCount() > 0);
765
766                 /**********************************************************************/
767                 /* WARNING this is not threadsafe!!                                   */
768                 /**********************************************************************/
769                 io::IFileArchive* opened_zip =
770                         fs->getFileArchive(fs->getFileArchiveCount()-1);
771
772                 const io::IFileList* files_in_zip = opened_zip->getFileList();
773
774                 unsigned int number_of_files = files_in_zip->getFileCount();
775
776                 for (unsigned int i=0; i < number_of_files; i++) {
777                         std::string fullpath = destination;
778                         fullpath += DIR_DELIM;
779                         fullpath += files_in_zip->getFullFileName(i).c_str();
780                         std::string fullpath_dir = fs::RemoveLastPathComponent(fullpath);
781
782                         if (!files_in_zip->isDirectory(i)) {
783                                 if (!fs::PathExists(fullpath_dir) && !fs::CreateAllDirs(fullpath_dir)) {
784                                         fs->removeFileArchive(fs->getFileArchiveCount()-1);
785                                         lua_pushboolean(L,false);
786                                         return 1;
787                                 }
788
789                                 io::IReadFile* toread = opened_zip->createAndOpenFile(i);
790
791                                 FILE *targetfile = fopen(fullpath.c_str(),"wb");
792
793                                 if (targetfile == NULL) {
794                                         fs->removeFileArchive(fs->getFileArchiveCount()-1);
795                                         lua_pushboolean(L,false);
796                                         return 1;
797                                 }
798
799                                 char read_buffer[1024];
800                                 long total_read = 0;
801
802                                 while (total_read < toread->getSize()) {
803
804                                         unsigned int bytes_read =
805                                                         toread->read(read_buffer,sizeof(read_buffer));
806                                         if ((bytes_read == 0 ) ||
807                                                 (fwrite(read_buffer, 1, bytes_read, targetfile) != bytes_read))
808                                         {
809                                                 fclose(targetfile);
810                                                 fs->removeFileArchive(fs->getFileArchiveCount()-1);
811                                                 lua_pushboolean(L,false);
812                                                 return 1;
813                                         }
814                                         total_read += bytes_read;
815                                 }
816
817                                 fclose(targetfile);
818                         }
819
820                 }
821
822                 fs->removeFileArchive(fs->getFileArchiveCount()-1);
823                 lua_pushboolean(L,true);
824                 return 1;
825         }
826
827         lua_pushboolean(L,false);
828         return 1;
829 }
830
831 /******************************************************************************/
832 int ModApiMainMenu::l_get_mainmenu_path(lua_State *L)
833 {
834         GUIEngine* engine = getGuiEngine(L);
835         sanity_check(engine != NULL);
836
837         lua_pushstring(L,engine->getScriptDir().c_str());
838         return 1;
839 }
840
841 /******************************************************************************/
842 bool ModApiMainMenu::isMinetestPath(std::string path)
843 {
844         if (fs::PathStartsWith(path,fs::TempPath()))
845                 return true;
846
847         /* games */
848         if (fs::PathStartsWith(path,fs::RemoveRelativePathComponents(porting::path_share + DIR_DELIM + "games")))
849                 return true;
850
851         /* mods */
852         if (fs::PathStartsWith(path,fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM + "mods")))
853                 return true;
854
855         /* mods */
856         if (fs::PathStartsWith(path,fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM + "textures")))
857                 return true;
858
859         /* worlds */
860         if (fs::PathStartsWith(path,fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM + "worlds")))
861                 return true;
862
863
864         return false;
865 }
866
867 /******************************************************************************/
868 int ModApiMainMenu::l_show_path_select_dialog(lua_State *L)
869 {
870         GUIEngine* engine = getGuiEngine(L);
871         sanity_check(engine != NULL);
872
873         const char *formname= luaL_checkstring(L, 1);
874         const char *title       = luaL_checkstring(L, 2);
875         bool is_file_select = readParam<bool>(L, 3);
876
877         GUIFileSelectMenu* fileOpenMenu =
878                 new GUIFileSelectMenu(RenderingEngine::get_gui_env(),
879                                                                 engine->m_parent,
880                                                                 -1,
881                                                                 engine->m_menumanager,
882                                                                 title,
883                                                                 formname,
884                                                                 is_file_select);
885         fileOpenMenu->setTextDest(engine->m_buttonhandler);
886         fileOpenMenu->drop();
887         return 0;
888 }
889
890 /******************************************************************************/
891 int ModApiMainMenu::l_download_file(lua_State *L)
892 {
893         const char *url    = luaL_checkstring(L, 1);
894         const char *target = luaL_checkstring(L, 2);
895
896         //check path
897         std::string absolute_destination = fs::RemoveRelativePathComponents(target);
898
899         if (ModApiMainMenu::isMinetestPath(absolute_destination)) {
900                 if (GUIEngine::downloadFile(url,absolute_destination)) {
901                         lua_pushboolean(L,true);
902                         return 1;
903                 }
904         } else {
905                 errorstream << "DOWNLOAD denied: " << absolute_destination
906                                 << " isn't a allowed path" << std::endl;
907         }
908         lua_pushboolean(L,false);
909         return 1;
910 }
911
912 /******************************************************************************/
913 int ModApiMainMenu::l_get_video_drivers(lua_State *L)
914 {
915         std::vector<irr::video::E_DRIVER_TYPE> drivers = RenderingEngine::getSupportedVideoDrivers();
916
917         lua_newtable(L);
918         for (u32 i = 0; i != drivers.size(); i++) {
919                 const char *name  = RenderingEngine::getVideoDriverName(drivers[i]);
920                 const char *fname = RenderingEngine::getVideoDriverFriendlyName(drivers[i]);
921
922                 lua_newtable(L);
923                 lua_pushstring(L, name);
924                 lua_setfield(L, -2, "name");
925                 lua_pushstring(L, fname);
926                 lua_setfield(L, -2, "friendly_name");
927
928                 lua_rawseti(L, -2, i + 1);
929         }
930
931         return 1;
932 }
933
934 /******************************************************************************/
935 int ModApiMainMenu::l_get_video_modes(lua_State *L)
936 {
937         std::vector<core::vector3d<u32> > videomodes
938                 = RenderingEngine::getSupportedVideoModes();
939
940         lua_newtable(L);
941         for (u32 i = 0; i != videomodes.size(); i++) {
942                 lua_newtable(L);
943                 lua_pushnumber(L, videomodes[i].X);
944                 lua_setfield(L, -2, "w");
945                 lua_pushnumber(L, videomodes[i].Y);
946                 lua_setfield(L, -2, "h");
947                 lua_pushnumber(L, videomodes[i].Z);
948                 lua_setfield(L, -2, "depth");
949
950                 lua_rawseti(L, -2, i + 1);
951         }
952
953         return 1;
954 }
955
956 /******************************************************************************/
957 int ModApiMainMenu::l_gettext(lua_State *L)
958 {
959         std::string text = strgettext(std::string(luaL_checkstring(L, 1)));
960         lua_pushstring(L, text.c_str());
961
962         return 1;
963 }
964
965 /******************************************************************************/
966 int ModApiMainMenu::l_get_screen_info(lua_State *L)
967 {
968         lua_newtable(L);
969         int top = lua_gettop(L);
970         lua_pushstring(L,"density");
971         lua_pushnumber(L,RenderingEngine::getDisplayDensity());
972         lua_settable(L, top);
973
974         lua_pushstring(L,"display_width");
975         lua_pushnumber(L,RenderingEngine::getDisplaySize().X);
976         lua_settable(L, top);
977
978         lua_pushstring(L,"display_height");
979         lua_pushnumber(L,RenderingEngine::getDisplaySize().Y);
980         lua_settable(L, top);
981
982         const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize();
983         lua_pushstring(L,"window_width");
984         lua_pushnumber(L, window_size.X);
985         lua_settable(L, top);
986
987         lua_pushstring(L,"window_height");
988         lua_pushnumber(L, window_size.Y);
989         lua_settable(L, top);
990         return 1;
991 }
992
993 int ModApiMainMenu::l_get_package_list(lua_State *L)
994 {
995         std::string url = g_settings->get("contentdb_url");
996         std::vector<Package> packages = getPackagesFromURL(url + "/api/packages/");
997
998         // Make table
999         lua_newtable(L);
1000         int top = lua_gettop(L);
1001         unsigned int index = 1;
1002
1003         // Fill table
1004         for (const auto &package : packages) {
1005                 lua_pushnumber(L, index);
1006                 lua_newtable(L);
1007
1008                 int top_lvl2 = lua_gettop(L);
1009
1010                 lua_pushstring(L, "author");
1011                 lua_pushstring(L, package.author.c_str());
1012                 lua_settable  (L, top_lvl2);
1013
1014                 lua_pushstring(L, "name");
1015                 lua_pushstring(L, package.name.c_str());
1016                 lua_settable  (L, top_lvl2);
1017
1018                 lua_pushstring(L, "title");
1019                 lua_pushstring(L, package.title.c_str());
1020                 lua_settable  (L, top_lvl2);
1021
1022                 lua_pushstring(L, "type");
1023                 lua_pushstring(L, package.type.c_str());
1024                 lua_settable  (L, top_lvl2);
1025
1026                 lua_pushstring(L, "short_description");
1027                 lua_pushstring(L, package.shortDesc.c_str());
1028                 lua_settable  (L, top_lvl2);
1029
1030                 lua_pushstring (L, "release");
1031                 lua_pushinteger(L, package.release);
1032                 lua_settable   (L, top_lvl2);
1033
1034                 if (package.thumbnail != "") {
1035                         lua_pushstring(L, "thumbnail");
1036                         lua_pushstring(L, package.thumbnail.c_str());
1037                         lua_settable  (L, top_lvl2);
1038                 }
1039
1040                 lua_pushstring(L, "url");
1041                 lua_pushstring(L, package.getDownloadURL(url).c_str());
1042                 lua_settable  (L, top_lvl2);
1043
1044                 lua_settable(L, top);
1045                 index++;
1046         }
1047
1048         return 1;
1049 }
1050
1051 /******************************************************************************/
1052 int ModApiMainMenu::l_get_min_supp_proto(lua_State *L)
1053 {
1054         lua_pushinteger(L, CLIENT_PROTOCOL_VERSION_MIN);
1055         return 1;
1056 }
1057
1058 int ModApiMainMenu::l_get_max_supp_proto(lua_State *L)
1059 {
1060         lua_pushinteger(L, CLIENT_PROTOCOL_VERSION_MAX);
1061         return 1;
1062 }
1063
1064 /******************************************************************************/
1065 int ModApiMainMenu::l_do_async_callback(lua_State *L)
1066 {
1067         GUIEngine* engine = getGuiEngine(L);
1068
1069         size_t func_length, param_length;
1070         const char* serialized_func_raw = luaL_checklstring(L, 1, &func_length);
1071
1072         const char* serialized_param_raw = luaL_checklstring(L, 2, &param_length);
1073
1074         sanity_check(serialized_func_raw != NULL);
1075         sanity_check(serialized_param_raw != NULL);
1076
1077         std::string serialized_func = std::string(serialized_func_raw, func_length);
1078         std::string serialized_param = std::string(serialized_param_raw, param_length);
1079
1080         lua_pushinteger(L, engine->queueAsync(serialized_func, serialized_param));
1081
1082         return 1;
1083 }
1084
1085 /******************************************************************************/
1086 void ModApiMainMenu::Initialize(lua_State *L, int top)
1087 {
1088         API_FCT(update_formspec);
1089         API_FCT(set_clouds);
1090         API_FCT(get_textlist_index);
1091         API_FCT(get_table_index);
1092         API_FCT(get_worlds);
1093         API_FCT(get_games);
1094         API_FCT(get_content_info);
1095         API_FCT(start);
1096         API_FCT(close);
1097         API_FCT(get_favorites);
1098         API_FCT(show_keys_menu);
1099         API_FCT(create_world);
1100         API_FCT(delete_world);
1101         API_FCT(delete_favorite);
1102         API_FCT(set_background);
1103         API_FCT(set_topleft_text);
1104         API_FCT(get_mapgen_names);
1105         API_FCT(get_modpath);
1106         API_FCT(get_clientmodpath);
1107         API_FCT(get_gamepath);
1108         API_FCT(get_texturepath);
1109         API_FCT(get_texturepath_share);
1110         API_FCT(create_dir);
1111         API_FCT(delete_dir);
1112         API_FCT(copy_dir);
1113         API_FCT(extract_zip);
1114         API_FCT(get_mainmenu_path);
1115         API_FCT(show_path_select_dialog);
1116         API_FCT(download_file);
1117         API_FCT(gettext);
1118         API_FCT(get_video_drivers);
1119         API_FCT(get_video_modes);
1120         API_FCT(get_screen_info);
1121         API_FCT(get_package_list);
1122         API_FCT(get_min_supp_proto);
1123         API_FCT(get_max_supp_proto);
1124         API_FCT(do_async_callback);
1125 }
1126
1127 /******************************************************************************/
1128 void ModApiMainMenu::InitializeAsync(lua_State *L, int top)
1129 {
1130         API_FCT(get_worlds);
1131         API_FCT(get_games);
1132         API_FCT(get_favorites);
1133         API_FCT(get_mapgen_names);
1134         API_FCT(get_modpath);
1135         API_FCT(get_clientmodpath);
1136         API_FCT(get_gamepath);
1137         API_FCT(get_texturepath);
1138         API_FCT(get_texturepath_share);
1139         API_FCT(create_dir);
1140         API_FCT(delete_dir);
1141         API_FCT(copy_dir);
1142         //API_FCT(extract_zip); //TODO remove dependency to GuiEngine
1143         API_FCT(download_file);
1144         //API_FCT(gettext); (gettext lib isn't threadsafe)
1145         API_FCT(get_package_list);
1146 }