forked from DFHack/dfhack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCore.cpp
More file actions
3004 lines (2679 loc) · 94.1 KB
/
Core.cpp
File metadata and controls
3004 lines (2679 loc) · 94.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
https://github.com/peterix/dfhack
Copyright (c) 2009-2012 Petr Mrázek ([email protected])
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "Internal.h"
#include "Error.h"
#include "MemAccess.h"
#include "Core.h"
#include "DataDefs.h"
#include "Debug.h"
#include "Console.h"
#include "MiscUtils.h"
#include "Module.h"
#include "VersionInfoFactory.h"
#include "VersionInfo.h"
#include "PluginManager.h"
#include "ModuleFactory.h"
#include "RemoteServer.h"
#include "RemoteTools.h"
#include "LuaTools.h"
#include "DFHackVersion.h"
#include "md5wrapper.h"
#include "modules/DFSDL.h"
#include "modules/DFSteam.h"
#include "modules/EventManager.h"
#include "modules/Filesystem.h"
#include "modules/Gui.h"
#include "modules/Textures.h"
#include "modules/World.h"
#include "modules/Persistence.h"
#include "df/init.h"
#include "df/gamest.h"
#include "df/graphic.h"
#include "df/interfacest.h"
#include "df/plotinfost.h"
#include "df/viewscreen_dwarfmodest.h"
#include "df/viewscreen_export_regionst.h"
#include "df/viewscreen_game_cleanerst.h"
#include "df/viewscreen_loadgamest.h"
#include "df/viewscreen_new_regionst.h"
#include "df/viewscreen_savegamest.h"
#include "df/world.h"
#include "df/world_data.h"
#include <stdio.h>
#include <iomanip>
#include <stdlib.h>
#include <fstream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <cstdio>
#include <cstring>
#include <iterator>
#include <sstream>
#include <forward_list>
#include <type_traits>
#include <cstdarg>
#include <filesystem>
#include <SDL_events.h>
#ifdef _WIN32
#define NOMINMAX
#include <Windows.h>
#endif
#ifdef LINUX_BUILD
#include <dlfcn.h>
#endif
using namespace DFHack;
using namespace df::enums;
using df::global::init;
using df::global::world;
using std::string;
// FIXME: A lot of code in one file, all doing different things... there's something fishy about it.
static bool parseKeySpec(std::string keyspec, int *psym, int *pmod, std::string *pfocus = NULL);
size_t loadScriptFiles(Core* core, color_ostream& out, const std::vector<std::string>& prefix, const std::filesystem::path& folder);
namespace DFHack {
DBG_DECLARE(core, keybinding, DebugCategory::LINFO);
DBG_DECLARE(core, script, DebugCategory::LINFO);
static const std::filesystem::path getConfigPath()
{
return Filesystem::getInstallDir() / "dfhack-config";
};
static const std::filesystem::path getConfigDefaultsPath()
{
return Filesystem::getInstallDir() / "hack" / "data" / "dfhack-config-defaults";
};
class MainThread {
public:
//! MainThread::suspend keeps the main DF thread suspended from Core::Init to
//! thread exit.
static CoreSuspenderBase& suspend() {
static thread_local CoreSuspenderBase lock{};
return lock;
}
};
}
struct Core::Private
{
std::thread iothread;
std::thread hotkeythread;
bool last_autosave_request{false};
bool last_manual_save_request{false};
bool was_load_save{false};
};
void PerfCounters::reset(bool ignorePauseState) {
*this = {};
ignore_pause_state = ignorePauseState;
baseline_elapsed_ms = Core::getInstance().p->getTickCount();
}
void PerfCounters::incCounter(uint32_t &counter, uint32_t baseline_ms) {
if (!ignore_pause_state && (!World::isFortressMode() || World::ReadPauseState()))
return;
counter += Core::getInstance().p->getTickCount() - baseline_ms;
}
bool PerfCounters::getIgnorePauseState() {
return ignore_pause_state;
}
uint32_t PerfCounters::registerTick(uint32_t baseline_ms) {
if (!World::isFortressMode() || World::ReadPauseState()) {
last_tick_baseline_ms = 0;
return 0;
}
// only update when the tick counter has advanced
if (!world || last_frame_counter == world->frame_counter)
return 0;
last_frame_counter = world->frame_counter;
if (last_tick_baseline_ms == 0) {
last_tick_baseline_ms = baseline_ms;
return 0;
}
uint32_t elapsed_ms = baseline_ms - last_tick_baseline_ms;
last_tick_baseline_ms = baseline_ms;
recent_ticks.head_idx = (recent_ticks.head_idx + 1) % RECENT_TICKS_HISTORY_SIZE;
if (recent_ticks.full)
recent_ticks.sum_ms -= recent_ticks.history[recent_ticks.head_idx];
else if (recent_ticks.head_idx == 0)
recent_ticks.full = true;
recent_ticks.history[recent_ticks.head_idx] = elapsed_ms;
recent_ticks.sum_ms += elapsed_ms;
return elapsed_ms;
}
uint32_t PerfCounters::getUnpausedFps() {
uint32_t seconds = recent_ticks.sum_ms / 1000;
if (seconds == 0)
return 0;
size_t num_frames = recent_ticks.full ? RECENT_TICKS_HISTORY_SIZE : recent_ticks.head_idx;
return num_frames / seconds;
}
struct CommandDepthCounter
{
static const int MAX_DEPTH = 20;
static thread_local int depth;
CommandDepthCounter() { depth++; }
~CommandDepthCounter() { depth--; }
bool ok() { return depth < MAX_DEPTH; }
};
thread_local int CommandDepthCounter::depth = 0;
void Core::cheap_tokenise(std::string const& input, std::vector<std::string>& output)
{
std::string *cur = NULL;
size_t i = 0;
// Check the first non-space character
while (i < input.size() && isspace(input[i])) i++;
// Special verbatim argument mode?
if (i < input.size() && input[i] == ':')
{
// Read the command
std::string cmd;
i++;
while (i < input.size() && !isspace(input[i]))
cmd.push_back(input[i++]);
if (!cmd.empty())
output.push_back(cmd);
// Find the argument
while (i < input.size() && isspace(input[i])) i++;
if (i < input.size())
output.push_back(input.substr(i));
return;
}
// Otherwise, parse in the regular quoted mode
for (; i < input.size(); i++)
{
unsigned char c = input[i];
if (isspace(c)) {
cur = NULL;
} else {
if (!cur) {
output.push_back("");
cur = &output.back();
}
if (c == '"') {
for (i++; i < input.size(); i++) {
c = input[i];
if (c == '"')
break;
else if (c == '\\') {
if (++i < input.size())
cur->push_back(input[i]);
}
else
cur->push_back(c);
}
} else {
cur->push_back(c);
}
}
}
}
struct IODATA
{
Core * core;
PluginManager * plug_mgr;
};
// A thread function... for handling hotkeys. This is needed because
// all the plugin commands are expected to be run from foreign threads.
// Running them from one of the main DF threads will result in deadlock!
static void fHKthread(IODATA * iodata)
{
Core * core = iodata->core;
PluginManager * plug_mgr = iodata->plug_mgr;
if(plug_mgr == 0 || core == 0)
{
std::cerr << "Hotkey thread has croaked." << std::endl;
return;
}
bool keep_going = true;
while(keep_going)
{
std::string stuff = core->getHotkeyCmd(keep_going); // waits on mutex!
if(!stuff.empty())
{
color_ostream_proxy out(core->getConsole());
auto rv = core->runCommand(out, stuff);
if (rv == CR_NOT_IMPLEMENTED)
out.printerr("Invalid hotkey command: '%s'\n", stuff.c_str());
}
}
}
struct sortable
{
bool recolor;
std::string name;
std::string description;
//FIXME: Nuke when MSVC stops failing at being C++11 compliant
sortable(bool recolor_,const std::string& name_,const std::string & description_): recolor(recolor_), name(name_), description(description_){};
bool operator <(const sortable & rhs) const
{
if( name < rhs.name )
return true;
return false;
};
};
static std::string dfhack_version_desc()
{
std::stringstream s;
s << Version::dfhack_version() << " ";
if (Version::is_release())
s << "(release)";
else
s << "(git: " << Version::git_commit(true) << ")";
s << " on " << (sizeof(void*) == 8 ? "x86_64" : "x86");
if (strlen(Version::dfhack_build_id()))
s << " [build ID: " << Version::dfhack_build_id() << "]";
return s.str();
}
static bool init_run_script(color_ostream &out, lua_State *state, const std::string& pcmd, std::vector<std::string>& pargs)
{
if (!lua_checkstack(state, pargs.size()+10))
return false;
Lua::PushDFHack(state);
lua_getfield(state, -1, "run_script");
lua_remove(state, -2);
lua_pushstring(state, pcmd.c_str());
for (auto& arg : pargs)
lua_pushstring(state, arg.c_str());
return true;
}
static command_result runLuaScript(color_ostream &out, std::string name, std::vector<std::string> &args)
{
using namespace std::placeholders;
auto init_fn = std::bind(init_run_script, _1, _2, name, args);
bool ok = Lua::RunCoreQueryLoop(out, DFHack::Core::getInstance().getLuaState(true), init_fn);
return ok ? CR_OK : CR_FAILURE;
}
static bool init_enable_script(color_ostream &out, lua_State *state, std::string& name, bool enable)
{
if (!lua_checkstack(state, 4))
return false;
Lua::PushDFHack(state);
lua_getfield(state, -1, "enable_script");
lua_remove(state, -2);
lua_pushstring(state, name.c_str());
lua_pushboolean(state, enable);
return true;
}
static command_result enableLuaScript(color_ostream &out, std::string name, bool state)
{
using namespace std::placeholders;
auto init_fn = std::bind(init_enable_script, _1, _2, name, state);
bool ok = Lua::RunCoreQueryLoop(out, DFHack::Core::getInstance().getLuaState(), init_fn);
return ok ? CR_OK : CR_FAILURE;
}
command_result Core::runCommand(color_ostream &out, const std::string &command)
{
if (!command.empty())
{
std::vector <std::string> parts;
Core::cheap_tokenise(command,parts);
if(parts.size() == 0)
return CR_NOT_IMPLEMENTED;
std::string first = parts[0];
parts.erase(parts.begin());
if (first[0] == '#')
return CR_OK;
std::cerr << "Invoking: " << command << std::endl;
return runCommand(out, first, parts);
}
else
return CR_NOT_IMPLEMENTED;
}
bool is_builtin(color_ostream &con, const std::string &command) {
CoreSuspender suspend;
auto L = DFHack::Core::getInstance().getLuaState();
Lua::StackUnwinder top(L);
if (!lua_checkstack(L, 1) ||
!Lua::PushModulePublic(con, L, "helpdb", "is_builtin")) {
con.printerr("Failed to load helpdb Lua code\n");
return false;
}
Lua::Push(L, command);
if (!Lua::SafeCall(con, L, 1, 1)) {
con.printerr("Failed Lua call to helpdb.is_builtin.\n");
return false;
}
return lua_toboolean(L, -1);
}
void get_commands(color_ostream &con, std::vector<std::string> &commands) {
ConditionalCoreSuspender suspend{};
if (!suspend) {
con.printerr("Cannot acquire core lock in helpdb.get_commands\n");
commands.clear();
return;
}
auto L = DFHack::Core::getInstance().getLuaState();
Lua::StackUnwinder top(L);
if (!lua_checkstack(L, 1) ||
!Lua::PushModulePublic(con, L, "helpdb", "get_commands")) {
con.printerr("Failed to load helpdb Lua code\n");
return;
}
if (!Lua::SafeCall(con, L, 0, 1)) {
con.printerr("Failed Lua call to helpdb.get_commands.\n");
}
Lua::GetVector(L, commands, top + 1);
}
static bool try_autocomplete(color_ostream &con, const std::string &first, std::string &completed)
{
std::vector<std::string> commands, possible;
get_commands(con, commands);
for (auto &command : commands)
if (command.substr(0, first.size()) == first)
possible.push_back(command);
if (possible.size() == 1)
{
completed = possible[0];
//fprintf(stderr, "Autocompleted %s to %s\n", , );
con.printerr("%s is not recognized. Did you mean %s?\n", first.c_str(), completed.c_str());
return true;
}
if (possible.size() > 1 && possible.size() < 8)
{
std::string out;
for (size_t i = 0; i < possible.size(); i++)
out += " " + possible[i];
con.printerr("%s is not recognized. Possible completions:%s\n", first.c_str(), out.c_str());
return true;
}
return false;
}
bool Core::addScriptPath(std::filesystem::path path, bool search_before)
{
std::lock_guard<std::mutex> lock(script_path_mutex);
auto &vec = script_paths[search_before ? 0 : 1];
if (std::find(vec.begin(), vec.end(), path) != vec.end())
return false;
if (!Filesystem::isdir(path))
return false;
vec.push_back(path);
return true;
}
bool Core::setModScriptPaths(const std::vector<std::filesystem::path> &mod_script_paths) {
std::lock_guard<std::mutex> lock(script_path_mutex);
script_paths[2] = mod_script_paths;
return true;
}
bool Core::removeScriptPath(std::filesystem::path path)
{
std::lock_guard<std::mutex> lock(script_path_mutex);
bool found = false;
for (int i = 0; i < 2; i++)
{
auto &vec = script_paths[i];
while (1)
{
auto it = std::find(vec.begin(), vec.end(), path);
if (it == vec.end())
break;
vec.erase(it);
found = true;
}
}
return found;
}
void Core::getScriptPaths(std::vector<std::filesystem::path> *dest)
{
std::lock_guard<std::mutex> lock(script_path_mutex);
dest->clear();
std::filesystem::path df_pref_path = Filesystem::getBaseDir();
std::filesystem::path df_install_path = Filesystem::getInstallDir();
for (auto & path : script_paths[0])
dest->emplace_back(path);
// should this be df_pref_path? probably
dest->push_back(getConfigPath() / "scripts");
if (df::global::world && isWorldLoaded()) {
std::string save = World::ReadWorldFolder();
if (save.size())
dest->emplace_back(df_pref_path / "save" / save / "scripts");
}
dest->emplace_back(df_install_path / "hack" / "scripts");
for (auto & path : script_paths[2])
dest->emplace_back(path);
for (auto & path : script_paths[1])
dest->emplace_back(path);
}
std::filesystem::path Core::findScript(std::string name)
{
std::vector<std::filesystem::path> paths;
getScriptPaths(&paths);
for (auto it = paths.begin(); it != paths.end(); ++it)
{
std::filesystem::path path = std::filesystem::weakly_canonical(*it / name);
if (Filesystem::isfile(path))
return path;
}
return {};
}
bool loadScriptPaths(color_ostream &out, bool silent = false)
{
std::filesystem::path filename{ getConfigPath() / "script-paths.txt" };
std::ifstream file(filename);
if (!file)
{
if (!silent)
out.printerr("Could not load %s\n", filename.c_str());
return false;
}
std::string raw;
int line = 0;
while (getline(file, raw))
{
++line;
std::istringstream ss(raw);
char ch;
ss >> std::skipws;
if (!(ss >> ch) || ch == '#')
continue;
ss >> std::ws; // discard whitespace
std::string path;
getline(ss, path);
if (ch == '+' || ch == '-')
{
if (!Core::getInstance().addScriptPath(path, ch == '+') && !silent)
out.printerr("%s:%i: Failed to add path: %s\n", filename.c_str(), line, path.c_str());
}
else if (!silent)
out.printerr("%s:%i: Illegal character: %c\n", filename.c_str(), line, ch);
}
return true;
}
static void loadModScriptPaths(color_ostream &out) {
std::vector<std::string> mod_script_paths_str;
std::vector<std::filesystem::path> mod_script_paths;
Lua::CallLuaModuleFunction(out, "script-manager", "get_mod_script_paths", {}, 1,
[&](lua_State *L) {
Lua::GetVector(L, mod_script_paths_str);
});
DEBUG(script,out).print("final mod script paths:\n");
for (auto& path : mod_script_paths_str)
{
DEBUG(script, out).print(" %s\n", path.c_str());
mod_script_paths.push_back(std::filesystem::weakly_canonical(std::filesystem::path{ path }));
}
Core::getInstance().setModScriptPaths(mod_script_paths);
}
static std::map<std::string, state_change_event> state_change_event_map;
static void sc_event_map_init() {
if (!state_change_event_map.size())
{
#define insert(name) state_change_event_map.insert(std::pair<std::string, state_change_event>(#name, name))
insert(SC_WORLD_LOADED);
insert(SC_WORLD_UNLOADED);
insert(SC_MAP_LOADED);
insert(SC_MAP_UNLOADED);
insert(SC_VIEWSCREEN_CHANGED);
insert(SC_PAUSED);
insert(SC_UNPAUSED);
#undef insert
}
}
static state_change_event sc_event_id (std::string name) {
sc_event_map_init();
auto it = state_change_event_map.find(name);
if (it != state_change_event_map.end())
return it->second;
if (name.find("SC_") != 0)
return sc_event_id(std::string("SC_") + name);
return SC_UNKNOWN;
}
static std::string sc_event_name (state_change_event id) {
sc_event_map_init();
for (auto it = state_change_event_map.begin(); it != state_change_event_map.end(); ++it)
{
if (it->second == id)
return it->first;
}
return "SC_UNKNOWN";
}
void help_helper(color_ostream &con, const std::string &entry_name) {
ConditionalCoreSuspender suspend{};
if (!suspend) {
con.printerr("Failed Lua call to helpdb.help (could not acquire core lock).\n");
return;
}
auto L = DFHack::Core::getInstance().getLuaState();
Lua::StackUnwinder top(L);
if (!lua_checkstack(L, 2) ||
!Lua::PushModulePublic(con, L, "helpdb", "help")) {
con.printerr("Failed to load helpdb Lua code\n");
return;
}
Lua::Push(L, entry_name);
if (!Lua::SafeCall(con, L, 1, 0)) {
con.printerr("Failed Lua call to helpdb.help.\n");
}
}
void tags_helper(color_ostream &con, const std::string &tag) {
ConditionalCoreSuspender suspend{};
if (!suspend) {
con.printerr("Failed Lua call to helpdb.help (could not acquire core lock).\n");
return;
}
auto L = DFHack::Core::getInstance().getLuaState();
Lua::StackUnwinder top(L);
if (!lua_checkstack(L, 1) ||
!Lua::PushModulePublic(con, L, "helpdb", "tags")) {
con.printerr("Failed to load helpdb Lua code\n");
return;
}
Lua::Push(L, tag);
if (!Lua::SafeCall(con, L, 1, 0)) {
con.printerr("Failed Lua call to helpdb.tags.\n");
}
}
void ls_helper(color_ostream &con, const std::vector<std::string> ¶ms) {
std::vector<std::string> filter;
bool skip_tags = false;
bool show_dev_commands = false;
std::string exclude_strs = "";
bool in_exclude = false;
for (auto str : params) {
if (in_exclude)
exclude_strs = str;
else if (str == "--notags")
skip_tags = true;
else if (str == "--dev")
show_dev_commands = true;
else if (str == "--exclude")
in_exclude = true;
else
filter.push_back(str);
}
ConditionalCoreSuspender suspend{};
if (!suspend) {
con.printerr("Failed Lua call to helpdb.help (could not acquire core lock).\n");
return;
}
auto L = DFHack::Core::getInstance().getLuaState();
Lua::StackUnwinder top(L);
if (!lua_checkstack(L, 5) ||
!Lua::PushModulePublic(con, L, "helpdb", "ls")) {
con.printerr("Failed to load helpdb Lua code\n");
return;
}
Lua::PushVector(L, filter);
Lua::Push(L, skip_tags);
Lua::Push(L, show_dev_commands);
Lua::Push(L, exclude_strs);
if (!Lua::SafeCall(con, L, 4, 0)) {
con.printerr("Failed Lua call to helpdb.ls.\n");
}
}
command_result Core::runCommand(color_ostream &con, const std::string &first_, std::vector<std::string> &parts, bool no_autocomplete)
{
std::string first = first_;
CommandDepthCounter counter;
if (!counter.ok())
{
con.printerr("Cannot invoke \"%s\": maximum command depth exceeded (%i)\n",
first.c_str(), CommandDepthCounter::MAX_DEPTH);
return CR_FAILURE;
}
if (first.empty())
return CR_NOT_IMPLEMENTED;
if (first.find('\\') != std::string::npos)
{
con.printerr("Replacing backslashes with forward slashes in \"%s\"\n", first.c_str());
for (size_t i = 0; i < first.size(); i++)
{
if (first[i] == '\\')
first[i] = '/';
}
}
// let's see what we actually got
command_result res;
if (first == "help" || first == "man" || first == "?")
{
if(!parts.size())
{
if (con.is_console())
{
con.print("This is the DFHack console. You can type commands in and manage DFHack plugins from it.\n"
"Some basic editing capabilities are included (single-line text editing).\n"
"The console also has a command history - you can navigate it with Up and Down keys.\n"
"On Windows, you may have to resize your console window. The appropriate menu is accessible\n"
"by clicking on the program icon in the top bar of the window.\n\n");
}
con.print("Here are some basic commands to get you started:\n"
" help|?|man - This text.\n"
" help <tool> - Usage help for the given plugin, command, or script.\n"
" tags - List the tags that the DFHack tools are grouped by.\n"
" ls|dir [<filter>] - List commands, optionally filtered by a tag or substring.\n"
" Optional parameters:\n"
" --notags: skip printing tags for each command.\n"
" --dev: include commands intended for developers and modders.\n"
" cls|clear - Clear the console.\n"
" fpause - Force DF to pause.\n"
" die - Force DF to close immediately, without saving.\n"
" keybinding - Modify bindings of commands to in-game key shortcuts.\n"
"\n"
"See more commands by running 'ls'.\n\n"
);
con.print("DFHack version %s\n", dfhack_version_desc().c_str());
}
else
{
help_helper(con, parts[0]);
}
}
else if (first == "tags")
{
tags_helper(con, parts.size() ? parts[0] : "");
}
else if (first == "load" || first == "unload" || first == "reload")
{
bool all = false;
bool load = (first == "load");
bool unload = (first == "unload");
bool reload = (first == "reload");
if (parts.size())
{
for (auto p = parts.begin(); p != parts.end(); p++)
{
if (p->size() && (*p)[0] == '-')
{
if (p->find('a') != std::string::npos)
all = true;
}
}
auto ret = CR_OK;
if (all)
{
if (load && !plug_mgr->loadAll())
ret = CR_FAILURE;
else if (unload && !plug_mgr->unloadAll())
ret = CR_FAILURE;
else if (reload && !plug_mgr->reloadAll())
ret = CR_FAILURE;
}
else
{
for (auto p = parts.begin(); p != parts.end(); p++)
{
if (!p->size() || (*p)[0] == '-')
continue;
if (load && !plug_mgr->load(*p))
ret = CR_FAILURE;
else if (unload && !plug_mgr->unload(*p))
ret = CR_FAILURE;
else if (reload && !plug_mgr->reload(*p))
ret = CR_FAILURE;
}
}
if (ret != CR_OK)
con.printerr("%s failed\n", first.c_str());
return ret;
}
else {
con.printerr("%s: no arguments\n", first.c_str());
return CR_FAILURE;
}
}
else if( first == "enable" || first == "disable" )
{
CoreSuspender suspend;
bool enable = (first == "enable");
if(parts.size())
{
for (size_t i = 0; i < parts.size(); i++)
{
std::string part = parts[i];
if (part.find('\\') != std::string::npos)
{
con.printerr("Replacing backslashes with forward slashes in \"%s\"\n", part.c_str());
for (size_t j = 0; j < part.size(); j++)
{
if (part[j] == '\\')
part[j] = '/';
}
}
part = GetAliasCommand(part, true);
Plugin * plug = (*plug_mgr)[part];
if(!plug)
{
std::filesystem::path lua = findScript(part + ".lua");
if (!lua.empty())
{
res = enableLuaScript(con, part, enable);
}
else
{
res = CR_NOT_FOUND;
con.printerr("No such plugin or Lua script: %s\n", part.c_str());
}
}
else if (!plug->can_set_enabled())
{
res = CR_NOT_IMPLEMENTED;
con.printerr("Cannot %s plugin: %s\n", first.c_str(), part.c_str());
}
else
{
res = plug->set_enabled(con, enable);
if (res != CR_OK || plug->is_enabled() != enable)
con.printerr("Could not %s plugin: %s\n", first.c_str(), part.c_str());
}
}
return res;
}
else
{
for (auto it = plug_mgr->begin(); it != plug_mgr->end(); ++it)
{
Plugin * plug = it->second;
if (!plug->can_be_enabled()) continue;
con.print(
"%21s %-3s%s\n",
(plug->getName()+":").c_str(),
plug->is_enabled() ? "on" : "off",
plug->can_set_enabled() ? "" : " (controlled internally)"
);
}
Lua::CallLuaModuleFunction(con, "script-manager", "list");
}
}
else if (first == "ls" || first == "dir")
{
ls_helper(con, parts);
}
else if (first == "plug")
{
const char *header_format = "%30s %10s %4s %8s\n";
const char *row_format = "%30s %10s %4i %8s\n";
con.print(header_format, "Name", "State", "Cmds", "Enabled");
plug_mgr->refresh();
for (auto it = plug_mgr->begin(); it != plug_mgr->end(); ++it)
{
Plugin * plug = it->second;
if (!plug)
continue;
if (parts.size() && std::find(parts.begin(), parts.end(), plug->getName()) == parts.end())
continue;
color_value color;
switch (plug->getState())
{
case Plugin::PS_LOADED:
color = COLOR_RESET;
break;
case Plugin::PS_UNLOADED:
case Plugin::PS_UNLOADING:
color = COLOR_YELLOW;
break;
case Plugin::PS_LOADING:
color = COLOR_LIGHTBLUE;
break;
case Plugin::PS_BROKEN:
color = COLOR_LIGHTRED;
break;
default:
color = COLOR_LIGHTMAGENTA;
break;
}
con.color(color);
con.print(row_format,
plug->getName().c_str(),
Plugin::getStateDescription(plug->getState()),
plug->size(),
(plug->can_be_enabled()
? (plug->is_enabled() ? "enabled" : "disabled")
: "n/a")
);
con.color(COLOR_RESET);
}
}
else if (first == "type")
{
if (!parts.size())
{
con.printerr("type: no argument\n");
return CR_WRONG_USAGE;
}
con << parts[0];
bool builtin = is_builtin(con, parts[0]);
std::filesystem::path lua_path = findScript(parts[0] + ".lua");
Plugin *plug = plug_mgr->getPluginByCommand(parts[0]);
if (builtin)
{
con << " is a built-in command";
con << std::endl;
}
else if (IsAlias(parts[0]))
{
con << " is an alias: " << GetAliasCommand(parts[0]) << std::endl;
}
else if (plug)
{
con << " is a command implemented by the plugin " << plug->getName() << std::endl;
}
else if (!lua_path.empty())
{
con << " is a Lua script: " << lua_path << std::endl;
}
else
{
con << " is not a recognized command." << std::endl;
plug = plug_mgr->getPluginByName(parts[0]);
if (plug)
con << "Plugin " << parts[0] << " exists and implements " << plug->size() << " commands." << std::endl;
return CR_FAILURE;
}
}
else if (first == "keybinding")
{
if (parts.size() >= 3 && (parts[0] == "set" || parts[0] == "add"))
{