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