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