]> git.lizzy.rs Git - dragonfireclient.git/blob - src/script/lua_api/l_mainmenu.cpp
Add /emergeblocks command and core.emerge_area() Lua API
[dragonfireclient.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 "emerge.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         lua_newtable(L);
710
711         std::list<const char *> names;
712         EmergeManager::getMapgenNames(names);
713
714         int i = 1;
715         for (std::list<const char *>::const_iterator
716                         it = names.begin(); it != names.end(); ++it) {
717                 lua_pushstring(L, *it);
718                 lua_rawseti(L, -2, i++);
719         }
720
721         return 1;
722 }
723
724
725 /******************************************************************************/
726 int ModApiMainMenu::l_get_modpath(lua_State *L)
727 {
728         std::string modpath
729                         = fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM + "mods" + DIR_DELIM);
730         lua_pushstring(L, modpath.c_str());
731         return 1;
732 }
733
734 /******************************************************************************/
735 int ModApiMainMenu::l_get_gamepath(lua_State *L)
736 {
737         std::string gamepath
738                         = fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM + "games" + DIR_DELIM);
739         lua_pushstring(L, gamepath.c_str());
740         return 1;
741 }
742
743 /******************************************************************************/
744 int ModApiMainMenu::l_get_texturepath(lua_State *L)
745 {
746         std::string gamepath
747                         = fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM + "textures");
748         lua_pushstring(L, gamepath.c_str());
749         return 1;
750 }
751
752 int ModApiMainMenu::l_get_texturepath_share(lua_State *L)
753 {
754         std::string gamepath
755                         = fs::RemoveRelativePathComponents(porting::path_share + DIR_DELIM + "textures");
756         lua_pushstring(L, gamepath.c_str());
757         return 1;
758 }
759
760 /******************************************************************************/
761 int ModApiMainMenu::l_create_dir(lua_State *L) {
762         const char *path        = luaL_checkstring(L, 1);
763
764         if (ModApiMainMenu::isMinetestPath(path)) {
765                 lua_pushboolean(L,fs::CreateAllDirs(path));
766                 return 1;
767         }
768         lua_pushboolean(L,false);
769         return 1;
770 }
771
772 /******************************************************************************/
773 int ModApiMainMenu::l_delete_dir(lua_State *L)
774 {
775         const char *path        = luaL_checkstring(L, 1);
776
777         std::string absolute_path = fs::RemoveRelativePathComponents(path);
778
779         if (ModApiMainMenu::isMinetestPath(absolute_path)) {
780                 lua_pushboolean(L,fs::RecursiveDelete(absolute_path));
781                 return 1;
782         }
783         lua_pushboolean(L,false);
784         return 1;
785 }
786
787 /******************************************************************************/
788 int ModApiMainMenu::l_copy_dir(lua_State *L)
789 {
790         const char *source      = luaL_checkstring(L, 1);
791         const char *destination = luaL_checkstring(L, 2);
792
793         bool keep_source = true;
794
795         if ((!lua_isnone(L,3)) &&
796                         (!lua_isnil(L,3))) {
797                 keep_source = lua_toboolean(L,3);
798         }
799
800         std::string absolute_destination = fs::RemoveRelativePathComponents(destination);
801         std::string absolute_source = fs::RemoveRelativePathComponents(source);
802
803         if ((ModApiMainMenu::isMinetestPath(absolute_source)) &&
804                         (ModApiMainMenu::isMinetestPath(absolute_destination))) {
805                 bool retval = fs::CopyDir(absolute_source,absolute_destination);
806
807                 if (retval && (!keep_source)) {
808
809                         retval &= fs::RecursiveDelete(absolute_source);
810                 }
811                 lua_pushboolean(L,retval);
812                 return 1;
813         }
814         lua_pushboolean(L,false);
815         return 1;
816 }
817
818 /******************************************************************************/
819 int ModApiMainMenu::l_extract_zip(lua_State *L)
820 {
821         GUIEngine* engine = getGuiEngine(L);
822         sanity_check(engine);
823
824         const char *zipfile     = luaL_checkstring(L, 1);
825         const char *destination = luaL_checkstring(L, 2);
826
827         std::string absolute_destination = fs::RemoveRelativePathComponents(destination);
828
829         if (ModApiMainMenu::isMinetestPath(absolute_destination)) {
830                 fs::CreateAllDirs(absolute_destination);
831
832                 io::IFileSystem* fs = engine->m_device->getFileSystem();
833
834                 if (!fs->addFileArchive(zipfile,true,false,io::EFAT_ZIP)) {
835                         lua_pushboolean(L,false);
836                         return 1;
837                 }
838
839                 sanity_check(fs->getFileArchiveCount() > 0);
840
841                 /**********************************************************************/
842                 /* WARNING this is not threadsafe!!                                   */
843                 /**********************************************************************/
844                 io::IFileArchive* opened_zip =
845                         fs->getFileArchive(fs->getFileArchiveCount()-1);
846
847                 const io::IFileList* files_in_zip = opened_zip->getFileList();
848
849                 unsigned int number_of_files = files_in_zip->getFileCount();
850
851                 for (unsigned int i=0; i < number_of_files; i++) {
852                         std::string fullpath = destination;
853                         fullpath += DIR_DELIM;
854                         fullpath += files_in_zip->getFullFileName(i).c_str();
855                         std::string fullpath_dir = fs::RemoveLastPathComponent(fullpath);
856
857                         if (!files_in_zip->isDirectory(i)) {
858                                 if (!fs::PathExists(fullpath_dir) && !fs::CreateAllDirs(fullpath_dir)) {
859                                         fs->removeFileArchive(fs->getFileArchiveCount()-1);
860                                         lua_pushboolean(L,false);
861                                         return 1;
862                                 }
863
864                                 io::IReadFile* toread = opened_zip->createAndOpenFile(i);
865
866                                 FILE *targetfile = fopen(fullpath.c_str(),"wb");
867
868                                 if (targetfile == NULL) {
869                                         fs->removeFileArchive(fs->getFileArchiveCount()-1);
870                                         lua_pushboolean(L,false);
871                                         return 1;
872                                 }
873
874                                 char read_buffer[1024];
875                                 long total_read = 0;
876
877                                 while (total_read < toread->getSize()) {
878
879                                         unsigned int bytes_read =
880                                                         toread->read(read_buffer,sizeof(read_buffer));
881                                         if ((bytes_read == 0 ) ||
882                                                 (fwrite(read_buffer, 1, bytes_read, targetfile) != bytes_read))
883                                         {
884                                                 fclose(targetfile);
885                                                 fs->removeFileArchive(fs->getFileArchiveCount()-1);
886                                                 lua_pushboolean(L,false);
887                                                 return 1;
888                                         }
889                                         total_read += bytes_read;
890                                 }
891
892                                 fclose(targetfile);
893                         }
894
895                 }
896
897                 fs->removeFileArchive(fs->getFileArchiveCount()-1);
898                 lua_pushboolean(L,true);
899                 return 1;
900         }
901
902         lua_pushboolean(L,false);
903         return 1;
904 }
905
906 /******************************************************************************/
907 int ModApiMainMenu::l_get_mainmenu_path(lua_State *L)
908 {
909         GUIEngine* engine = getGuiEngine(L);
910         sanity_check(engine != NULL);
911
912         lua_pushstring(L,engine->getScriptDir().c_str());
913         return 1;
914 }
915
916 /******************************************************************************/
917 bool ModApiMainMenu::isMinetestPath(std::string path)
918 {
919         if (fs::PathStartsWith(path,fs::TempPath()))
920                 return true;
921
922         /* games */
923         if (fs::PathStartsWith(path,fs::RemoveRelativePathComponents(porting::path_share + DIR_DELIM + "games")))
924                 return true;
925
926         /* mods */
927         if (fs::PathStartsWith(path,fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM + "mods")))
928                 return true;
929
930         /* worlds */
931         if (fs::PathStartsWith(path,fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM + "worlds")))
932                 return true;
933
934
935         return false;
936 }
937
938 /******************************************************************************/
939 int ModApiMainMenu::l_show_file_open_dialog(lua_State *L)
940 {
941         GUIEngine* engine = getGuiEngine(L);
942         sanity_check(engine != NULL);
943
944         const char *formname= luaL_checkstring(L, 1);
945         const char *title       = luaL_checkstring(L, 2);
946
947         GUIFileSelectMenu* fileOpenMenu =
948                 new GUIFileSelectMenu(engine->m_device->getGUIEnvironment(),
949                                                                 engine->m_parent,
950                                                                 -1,
951                                                                 engine->m_menumanager,
952                                                                 title,
953                                                                 formname);
954         fileOpenMenu->setTextDest(engine->m_buttonhandler);
955         fileOpenMenu->drop();
956         return 0;
957 }
958
959 /******************************************************************************/
960 int ModApiMainMenu::l_get_version(lua_State *L)
961 {
962         lua_pushstring(L, g_version_string);
963         return 1;
964 }
965
966 /******************************************************************************/
967 int ModApiMainMenu::l_sound_play(lua_State *L)
968 {
969         GUIEngine* engine = getGuiEngine(L);
970
971         SimpleSoundSpec spec;
972         read_soundspec(L, 1, spec);
973         bool looped = lua_toboolean(L, 2);
974
975         u32 handle = engine->playSound(spec, looped);
976
977         lua_pushinteger(L, handle);
978
979         return 1;
980 }
981
982 /******************************************************************************/
983 int ModApiMainMenu::l_sound_stop(lua_State *L)
984 {
985         GUIEngine* engine = getGuiEngine(L);
986
987         u32 handle = luaL_checkinteger(L, 1);
988         engine->stopSound(handle);
989
990         return 1;
991 }
992
993 /******************************************************************************/
994 int ModApiMainMenu::l_download_file(lua_State *L)
995 {
996         const char *url    = luaL_checkstring(L, 1);
997         const char *target = luaL_checkstring(L, 2);
998
999         //check path
1000         std::string absolute_destination = fs::RemoveRelativePathComponents(target);
1001
1002         if (ModApiMainMenu::isMinetestPath(absolute_destination)) {
1003                 if (GUIEngine::downloadFile(url,absolute_destination)) {
1004                         lua_pushboolean(L,true);
1005                         return 1;
1006                 }
1007         } else {
1008                 errorstream << "DOWNLOAD denied: " << absolute_destination
1009                                 << " isn't a allowed path" << std::endl;
1010         }
1011         lua_pushboolean(L,false);
1012         return 1;
1013 }
1014
1015 /******************************************************************************/
1016 int ModApiMainMenu::l_get_video_drivers(lua_State *L)
1017 {
1018         std::vector<irr::video::E_DRIVER_TYPE> drivers
1019                 = porting::getSupportedVideoDrivers();
1020
1021         lua_newtable(L);
1022         for (u32 i = 0; i != drivers.size(); i++) {
1023                 const char *name  = porting::getVideoDriverName(drivers[i]);
1024                 const char *fname = porting::getVideoDriverFriendlyName(drivers[i]);
1025
1026                 lua_newtable(L);
1027                 lua_pushstring(L, name);
1028                 lua_setfield(L, -2, "name");
1029                 lua_pushstring(L, fname);
1030                 lua_setfield(L, -2, "friendly_name");
1031
1032                 lua_rawseti(L, -2, i + 1);
1033         }
1034
1035         return 1;
1036 }
1037
1038 /******************************************************************************/
1039 int ModApiMainMenu::l_get_video_modes(lua_State *L)
1040 {
1041         std::vector<core::vector3d<u32> > videomodes
1042                 = porting::getSupportedVideoModes();
1043
1044         lua_newtable(L);
1045         for (u32 i = 0; i != videomodes.size(); i++) {
1046                 lua_newtable(L);
1047                 lua_pushnumber(L, videomodes[i].X);
1048                 lua_setfield(L, -2, "w");
1049                 lua_pushnumber(L, videomodes[i].Y);
1050                 lua_setfield(L, -2, "h");
1051                 lua_pushnumber(L, videomodes[i].Z);
1052                 lua_setfield(L, -2, "depth");
1053
1054                 lua_rawseti(L, -2, i + 1);
1055         }
1056
1057         return 1;
1058 }
1059
1060 /******************************************************************************/
1061 int ModApiMainMenu::l_gettext(lua_State *L)
1062 {
1063         std::wstring wtext = wstrgettext((std::string) luaL_checkstring(L, 1));
1064         lua_pushstring(L, wide_to_utf8(wtext).c_str());
1065
1066         return 1;
1067 }
1068
1069 /******************************************************************************/
1070 int ModApiMainMenu::l_get_screen_info(lua_State *L)
1071 {
1072         lua_newtable(L);
1073         int top = lua_gettop(L);
1074         lua_pushstring(L,"density");
1075         lua_pushnumber(L,porting::getDisplayDensity());
1076         lua_settable(L, top);
1077
1078         lua_pushstring(L,"display_width");
1079         lua_pushnumber(L,porting::getDisplaySize().X);
1080         lua_settable(L, top);
1081
1082         lua_pushstring(L,"display_height");
1083         lua_pushnumber(L,porting::getDisplaySize().Y);
1084         lua_settable(L, top);
1085
1086         lua_pushstring(L,"window_width");
1087         lua_pushnumber(L,porting::getWindowSize().X);
1088         lua_settable(L, top);
1089
1090         lua_pushstring(L,"window_height");
1091         lua_pushnumber(L,porting::getWindowSize().Y);
1092         lua_settable(L, top);
1093         return 1;
1094 }
1095
1096 /******************************************************************************/
1097 int ModApiMainMenu::l_get_min_supp_proto(lua_State *L)
1098 {
1099         lua_pushinteger(L, CLIENT_PROTOCOL_VERSION_MIN);
1100         return 1;
1101 }
1102
1103 int ModApiMainMenu::l_get_max_supp_proto(lua_State *L)
1104 {
1105         lua_pushinteger(L, CLIENT_PROTOCOL_VERSION_MAX);
1106         return 1;
1107 }
1108
1109 /******************************************************************************/
1110 int ModApiMainMenu::l_do_async_callback(lua_State *L)
1111 {
1112         GUIEngine* engine = getGuiEngine(L);
1113
1114         size_t func_length, param_length;
1115         const char* serialized_func_raw = luaL_checklstring(L, 1, &func_length);
1116
1117         const char* serialized_param_raw = luaL_checklstring(L, 2, &param_length);
1118
1119         sanity_check(serialized_func_raw != NULL);
1120         sanity_check(serialized_param_raw != NULL);
1121
1122         std::string serialized_func = std::string(serialized_func_raw, func_length);
1123         std::string serialized_param = std::string(serialized_param_raw, param_length);
1124
1125         lua_pushinteger(L, engine->queueAsync(serialized_func, serialized_param));
1126
1127         return 1;
1128 }
1129
1130 /******************************************************************************/
1131 void ModApiMainMenu::Initialize(lua_State *L, int top)
1132 {
1133         API_FCT(update_formspec);
1134         API_FCT(set_clouds);
1135         API_FCT(get_textlist_index);
1136         API_FCT(get_table_index);
1137         API_FCT(get_worlds);
1138         API_FCT(get_games);
1139         API_FCT(start);
1140         API_FCT(close);
1141         API_FCT(get_favorites);
1142         API_FCT(show_keys_menu);
1143         API_FCT(create_world);
1144         API_FCT(delete_world);
1145         API_FCT(delete_favorite);
1146         API_FCT(set_background);
1147         API_FCT(set_topleft_text);
1148         API_FCT(get_mapgen_names);
1149         API_FCT(get_modpath);
1150         API_FCT(get_gamepath);
1151         API_FCT(get_texturepath);
1152         API_FCT(get_texturepath_share);
1153         API_FCT(create_dir);
1154         API_FCT(delete_dir);
1155         API_FCT(copy_dir);
1156         API_FCT(extract_zip);
1157         API_FCT(get_mainmenu_path);
1158         API_FCT(show_file_open_dialog);
1159         API_FCT(get_version);
1160         API_FCT(download_file);
1161         API_FCT(get_modstore_details);
1162         API_FCT(get_modstore_list);
1163         API_FCT(sound_play);
1164         API_FCT(sound_stop);
1165         API_FCT(gettext);
1166         API_FCT(get_video_drivers);
1167         API_FCT(get_video_modes);
1168         API_FCT(get_screen_info);
1169         API_FCT(get_min_supp_proto);
1170         API_FCT(get_max_supp_proto);
1171         API_FCT(do_async_callback);
1172 }
1173
1174 /******************************************************************************/
1175 void ModApiMainMenu::InitializeAsync(AsyncEngine& engine)
1176 {
1177
1178         ASYNC_API_FCT(get_worlds);
1179         ASYNC_API_FCT(get_games);
1180         ASYNC_API_FCT(get_favorites);
1181         ASYNC_API_FCT(get_mapgen_names);
1182         ASYNC_API_FCT(get_modpath);
1183         ASYNC_API_FCT(get_gamepath);
1184         ASYNC_API_FCT(get_texturepath);
1185         ASYNC_API_FCT(get_texturepath_share);
1186         ASYNC_API_FCT(create_dir);
1187         ASYNC_API_FCT(delete_dir);
1188         ASYNC_API_FCT(copy_dir);
1189         //ASYNC_API_FCT(extract_zip); //TODO remove dependency to GuiEngine
1190         ASYNC_API_FCT(get_version);
1191         ASYNC_API_FCT(download_file);
1192         ASYNC_API_FCT(get_modstore_details);
1193         ASYNC_API_FCT(get_modstore_list);
1194         //ASYNC_API_FCT(gettext); (gettext lib isn't threadsafe)
1195 }