-
Notifications
You must be signed in to change notification settings - Fork 1
/
cfg.hpp
1315 lines (1063 loc) · 53.3 KB
/
cfg.hpp
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
// ================================================================================================
// -*- C++ -*-
// File: cfg.hpp
// Author: Guilherme R. Lampert
// Created on: 09/06/16
//
// About:
// Lib CFG - A small C++ library for configuration file handling, CVars and Commands.
//
// License:
// This software is in the public domain. Where that dedication is not recognized,
// you are granted a perpetual, irrevocable license to copy, distribute, and modify
// this file as you see fit. Source code is provided "as is", without warranty of any
// kind, express or implied. No attribution is required, but a mention about the author
// is appreciated.
// ================================================================================================
#ifndef CFG_HPP
#define CFG_HPP
#include <cstddef>
#include <cstdint>
#include <string>
#include <utility>
#include <functional>
#include <type_traits>
//
// Overridable assert() for Lib CFG.
// Defaults to the standard assert() function.
//
#ifndef CFG_ASSERT
#include <cassert>
#define CFG_ASSERT assert
#endif // CFG_ASSERT
//
// Having format string checking is nice, but this
// is not a mandatory feature to compile the library.
//
#if defined(__GNUC__) || defined(__clang__)
#define CFG_PRINTF_FUNC(fmtIndex, varIndex) __attribute__((format(printf, fmtIndex, varIndex)))
#else // !GNU && !Clang
#define CFG_PRINTF_FUNC(fmtIndex, varIndex) /* unimplemented */
#endif // GNU | Clang
//
// All public members of the CFG library are defined inside this namespace.
//
namespace cfg
{
class CVar;
class Command;
class CVarManager;
class CommandManager;
class SimpleCommandTerminal;
// ================================================================================================
//
// CVars - Configuration Variables
//
// ================================================================================================
// ========================================================
// CVar callbacks:
// ========================================================
//
// Optional value completion callback for CVars.
// Only the C-style callback variant is available for CVars.
// If none is provided on registration, the default
// allowed values are used for value auto-completion.
//
// First parameter is the partial argument or an empty string.
// Second is the output array of matched strings.
// Third is the size of the output array of strings.
//
// The expected returned value is the numbers of matches available
// (which can be greater than the output size), or -1 if there was an error.
//
using CVarValueCompletionCallback = int (*)(const char *, std::string *, int);
//
// Callback passed to CVarManager::enumerateAllCVars().
//
// First argument is the CVar being visited.
// Second argument is a user-provided "context" pointer
// that is forwarded from the enumerateAllCVars() call.
//
// Return true to continue the enumeration or false to break it.
//
using CVarEnumerateCallback = bool (*)(CVar *, void *);
// ========================================================
// class CVar:
// ========================================================
class CVar
{
public:
//
// Predefined CVar flags (user can extend these).
//
struct Flags final
{
// Marked as modified to eventually be written to a configuration file (internal use flag).
static constexpr std::uint32_t Modified = 1 << 0;
// Value persists after program termination and is restored in a future restart (saved to config file).
static constexpr std::uint32_t Persistent = 1 << 1;
// Value persists only while the program is running (never saved). Mutually exclusive with 'Persistent'.
static constexpr std::uint32_t Volatile = 1 << 2;
// For display only. Cannot be changed via Console/command line or the set*() methods.
static constexpr std::uint32_t ReadOnly = 1 << 3;
// Similar to 'ReadOnly' but can be set by the startup command line of the application.
static constexpr std::uint32_t InitOnly = 1 << 4;
// Enforces min/max bounds for number vars and allowed strings for string vars.
static constexpr std::uint32_t RangeCheck = 1 << 5;
// Variable was defined by the user via a 'set' command in the Console or via a config file.
static constexpr std::uint32_t UserDefined = 1 << 6;
};
//
// Type category flags.
//
enum class Type : std::uint8_t
{
Int,
Bool,
Float,
String,
Enum
};
//
// Number formatting/representations.
// Use these with 'setNumberFormat()' to define how number CVar are converted
// to strings and how string CVars are rendered when initialized from numbers.
//
enum class NumberFormat : std::uint8_t
{
Binary,
Octal,
Decimal,
Hexadecimal
};
public:
//
// CVar interface:
//
virtual ~CVar();
// Name and description cannot be changed after the CVar is created.
// Description is optional. If no description was provided, an empty string is returned.
virtual std::string getName() const = 0;
virtual std::string getDesc() const = 0;
virtual const char * getNameCString() const = 0;
virtual const char * getDescCString() const = 0;
// Get a printable string of the underlaying type for displaying.
// E.g.: "int" for integers, "float" for floats, "string" for strings, etc.
virtual std::string getTypeString() const = 0;
virtual const char * getTypeCString() const = 0;
// Get the type category of the underlaying wrapped value.
// Type cannot be changed once a CVar is constructed.
virtual Type getType() const = 0;
// Set the formatting used to convert numerical CVar values to
// printable strings, i.e.: binary, octal, decimal, hexadecimal.
// Initial formatting is decimal.
virtual NumberFormat getNumberFormat() const = 0;
virtual void setNumberFormat(NumberFormat format) = 0;
// User is free to query and change the CVar flags after construction.
virtual std::uint32_t getFlags() const = 0;
virtual void setFlags(std::uint32_t newFlags) = 0;
// Var flags to printable string or an empty string if flags = 0.
virtual std::string getFlagsString() const = 0;
// Direct access to the modified flag.
virtual void setModified() = 0;
virtual void clearModified() = 0;
// Test specific flags:
virtual bool isModified() const = 0;
virtual bool isWritable() const = 0;
virtual bool isPersistent() const = 0;
virtual bool isRangeChecked() const = 0;
// std::strcmp-style comparison of just the variable names.
virtual int compareNames(const CVar & other) const = 0;
// Does a deep comparison to determine if both instances are equivalent.
virtual bool compareEqual(const CVar & other) const = 0;
//
// CVar value access:
//
// The following set*() methods will fail with an error message
// if the variable is read-only or if there's no type conversion
// available. The get*() methods will fail with an error message
// if there is no conversion but sill return a default value
// (zero for numbers / false for boolean / empty string).
virtual std::int64_t getIntValue() const = 0;
virtual bool setIntValue(std::int64_t newValue) = 0;
virtual bool getBoolValue() const = 0;
virtual bool setBoolValue(bool newValue) = 0;
virtual double getFloatValue() const = 0;
virtual bool setFloatValue(double newValue) = 0;
virtual std::string getStringValue() const = 0;
virtual bool setStringValue(std::string newValue) = 0;
//
// Allowed value ranges and default/reset value:
//
// Get the allowed variable values as strings for displaying in the console/terminal.
// It will write up to 'maxValueStrings' in the output array. The returned value is the
// numbers of value strings available (which can be > maxValueStrings), or -1 if there was an error.
virtual int getAllowedValueStrings(std::string * outValueStrings, int maxValueStrings) const = 0;
// Get the total number of allowed variable values or zero if none.
// You can use this to allocate storage for getAllowedValueStrings().
virtual int getAllowedValueCount() const = 0;
// Rests the CVar to its default value and flags it as modified.
// ReadOnly/InitOnly CVars cannot be reset, not even to defaults.
virtual bool setDefaultValue() = 0;
// Get the default reset value as a string for Console/Terminal printing.
virtual std::string getDefaultValueString() const = 0;
// Similar to getAllowedValueStrings(), but will forward to an argument completion callback
// first if the CVar has one. If no callback is set, then it returns the allowed values.
virtual int valueCompletion(const char * partialVal, std::string * outMatches, int maxMatches) const = 0;
virtual CVarValueCompletionCallback getValueCompletionCallback() const = 0;
};
// ========================================================
// class CVarManager:
// ========================================================
class CVarManager
{
public:
//
// Allocator/factory:
//
static CVarManager * createInstance(int cvarHashTableSizeHint = 0);
static void destroyInstance(CVarManager * cvarManager);
//
// CVarManager interface:
//
// Destructor will also destroy all CVars registered with this manager.
virtual ~CVarManager();
// Finds previously registered CVar or returns null if no such var is registered.
virtual CVar * findCVar(const char * name) const = 0;
// Find vars with name starting with the 'partialName' substring.
// Returns the total number of matches found, which might be > than maxMatches,
// but only up to maxMatches will be written to the output array in any case.
// Returns a negative value in case of error. Output variables are sorted
// alphabetically according to name.
virtual int findCVarsWithPartialName(const char * partialName,
CVar ** outMatches,
int maxMatches) const = 0;
// Same as above, but get only the var names for displaying.
virtual int findCVarsWithPartialName(const char * partialName,
const char ** outMatches,
int maxMatches) const = 0;
// Similar to findCVarsWithPartialName(), but instead searches by var flags.
virtual int findCVarsWithFlags(std::uint32_t flags,
CVar ** outMatches,
int maxMatches) const = 0;
// Remove previously registered var by name or pointer. If this function
// succeeds, all pointers to the variable will also become invalid!
virtual bool removeCVar(const char * name) = 0;
virtual bool removeCVar(CVar * cvar) = 0;
// Unregisters and deletes all CVar instances that belong to this manager.
// Be careful when calling this method, since all external CVar pointers will
// be invalidated. The effect is equivalent to destroying the manager instance.
virtual void removeAllCVars() = 0;
// Number of CVar registered with this manager so far.
virtual int getRegisteredCVarsCount() const = 0;
// Tests if a string complies with the CVar naming rules.
// It DOES NOT check if the variable is already registered.
virtual bool isValidCVarName(const char * name) const = 0;
// Calls the supplied callback for each registered CVar.
// No specific iteration order is guaranteed.
virtual void enumerateAllCVars(CVarEnumerateCallback enumCallback, void * userContext) = 0;
//
// CVar registration:
//
// These will fail with an error and return null if a CVar
// with the same name already exits. Strings are copied, so
// you can throw away the pointers once the method returns.
//
virtual CVar * registerCVarBool(const char * name, const char * description, std::uint32_t flags,
bool initValue, CVarValueCompletionCallback completionCb = nullptr) = 0;
virtual CVar * registerCVarInt(const char * name, const char * description, std::uint32_t flags,
std::int64_t initValue, std::int64_t minValue, std::int64_t maxValue,
CVarValueCompletionCallback completionCb = nullptr) = 0;
virtual CVar * registerCVarFloat(const char * name, const char * description, std::uint32_t flags,
double initValue, double minValue, double maxValue,
CVarValueCompletionCallback completionCb = nullptr) = 0;
virtual CVar * registerCVarString(const char * name, const char * description, std::uint32_t flags,
const std::string & initValue, const char ** allowedStrings,
CVarValueCompletionCallback completionCb = nullptr) = 0;
virtual CVar * registerCVarEnum(const char * name, const char * description, std::uint32_t flags,
std::int64_t initValue, const std::int64_t * enumConstants, const char ** constNames,
CVarValueCompletionCallback completionCb = nullptr) = 0;
//
// CVar value queries:
//
// Get the value of a CVar by its name.
// If the CVar doesn't exit, and error is logged and
// you get a default value (zero/empty string).
//
virtual bool getCVarValueBool(const char * name) const = 0;
virtual std::int64_t getCVarValueInt(const char * name) const = 0;
virtual double getCVarValueFloat(const char * name) const = 0;
virtual std::string getCVarValueString(const char * name) const = 0;
//
// CVar value update with registration:
//
// Set the value of an existing CVar by its name or
// register a new CVar with defaults. The returned
// pointer will be the existing CVar that was set or
// the newly created one.
//
virtual CVar * setCVarValueBool(const char * name, bool value, std::uint32_t flags) = 0;
virtual CVar * setCVarValueInt(const char * name, std::int64_t value, std::uint32_t flags) = 0;
virtual CVar * setCVarValueFloat(const char * name, double value, std::uint32_t flags) = 0;
virtual CVar * setCVarValueString(const char * name, const std::string & value, std::uint32_t flags) = 0;
};
// ================================================================================================
//
// Console Commands
//
// ================================================================================================
// ========================================================
// Command system constants:
// ========================================================
constexpr int MaxCommandNameLength = 32; // Maximum length in chars of a command name, including the '\0'.
constexpr int MaxCommandDescLength = 100; // Max length in chars of the description comment user can attach to a command.
constexpr int MaxCommandArgStrLength = 2048; // Maximum length in chars of a string of arguments, including the '\0'.
constexpr int MaxCommandArguments = 64; // Maximum number of argument strings for a single command.
constexpr int MaxReentrantCommands = 999999; // If this many commands are executed in a single frame, there's probably a reentrant loop.
constexpr int CommandBufferSize = 65535; // Max length in chars of the command buffer used by CommandManager, including a '\0'.
constexpr char CommandTextSeparator = ';'; // Character assumed to be the separator between different commands on the same line.
// Command execution modes for CommandManager::execute() and friends.
// See also CommandManager::execNow(), execInsert() and execAppend().
enum class CommandExecMode
{
Immediate, // Immediate execution. Doesn't return until completed.
Insert, // Insert at current position (front) of the command buffer, but doesn't run it yet.
Append // Append to end of the command buffer for future execution by execBufferedCommands().
};
// ========================================================
// class CommandArgs:
// ========================================================
class CommandArgs final
{
public:
// Creates an empty CommandArgs.
CommandArgs();
// Construct from a string of arguments separated by whitespace.
// The first argument extracted is assumed to be the command/program
// name and will be available via 'getCommandName()' but won't be included
// in the argStrings[]. The command string may be preceded and followed by any
// number of whitespace chars. Sequences of quoted characters are assumed
// to be strings and are not split by whitespace, producing one argument.
// Single and double quotes can make a quoted block. Single quotes can
// appear inside a double-quoted block.
explicit CommandArgs(const char * cmdStr);
// Construct from a pre-split argc/argv array of strings, Unix-style.
// This can be used to copy the command line arguments from the main() function.
// First entry is assumed to be the program name; 'argc' is expected to be >= 1.
CommandArgs(int argc, const char * argv[]);
// Copy/assignment.
CommandArgs(const CommandArgs & other);
CommandArgs & operator = (const CommandArgs & other);
// Get the first argument (the command/program name).
const char * getCommandName() const noexcept;
// Number of argument strings parsed, NOT including the command/program name.
int getArgCount() const noexcept;
// Returns true if there are no arguments (argCount == 0).
bool isEmpty() const noexcept;
// Get the individual argument strings.
// Fails with an assertion if the index is out-of-bounds.
const char * operator[](int index) const;
const char * getArgAt(int index) const;
// Begin/end range to allow "range-based for" iteration of arguments.
// No validation done if you deref the end or a past-the-end pointer!
const char * const * begin() const noexcept;
const char * const * end() const noexcept;
// Compares a given argument index with the provided string.
// Return is equivalent to std::strcmp(). If argIndex < 0 || >= argCount, -1 is returned.
int compare(int argIndex, const char * str) const;
private:
void parseArgString(const char * argStr);
bool addArgString(const char * argStr);
const char * appendToken(const char * token, int tokenLen);
// Number of arguments parsed and inserted in the argStrings[] array.
int argCount;
// Index to the start of the next free slot in tokenizedArgStr[].
// Only used during command line parsing.
int nextTokenIndex;
// Extra pointer to the command/program name, which is assumed to be
// the first string of tokenizedArgStr[]. argStrings[] will refer to the
// parameters that follow the command name but won't include this name.
const char * cmdName;
// Array of arguments. Each one points to a slice of tokenizedArgStr[].
const char * argStrings[MaxCommandArguments];
// Tokenized string of arguments. Each arg is separated by a null char.
// Each entry in argStrings[] points to a slice of this buffer.
char tokenizedArgStr[MaxCommandArgStrLength];
};
// ========================================================
// Command callbacks:
// ========================================================
//
// Callback passed to CommandManager::enumerateAllCommands().
//
// First argument is the Command being visited.
// Second argument is a user-provided "context" pointer
// that is forwarded from the enumerateAllCommands() call.
//
// Return true to continue the enumeration or false to break it.
//
using CommandEnumerateCallback = bool (*)(Command *, void *);
//
// The "callback" interface uses plain function pointers.
// The last void* parameter is an optional pointer to a
// user provided "context" object.
//
using CommandHandlerCallback = void (*)(const CommandArgs &, void *);
using CommandArgCompletionCallback = int (*)(const char *, std::string *, int, void *);
//
// "Delegates" are the generic std::function interface,
// which can bind to plain functions or stateful lambdas.
//
using CommandHandlerDelegate = std::function<void(const CommandArgs &)>;
using CommandArgCompletionDelegate = std::function<int(const char *, std::string *, int)>;
//
// This specialized template class is a delegate for
// command handlers from pointers to member functions.
//
class CommandHandlerMemFunc final
{
public:
CommandHandlerMemFunc(const CommandHandlerMemFunc & other)
{
if (other.baseHolder != nullptr)
{
baseHolder = other.baseHolder->clone(&dataBlob);
CFG_ASSERT(baseHolder != nullptr);
}
}
CommandHandlerMemFunc & operator = (const CommandHandlerMemFunc & other)
{
if (other.baseHolder != nullptr)
{
baseHolder = other.baseHolder->clone(&dataBlob);
CFG_ASSERT(baseHolder != nullptr);
}
return *this;
}
template<typename RetType, typename ClassType, typename... Args>
CommandHandlerMemFunc(ClassType * objPtr, RetType (ClassType::*pMemFunc)(Args...))
{
const auto holder = MemFuncHolder<RetType, ClassType, Args...>{ objPtr, pMemFunc };
baseHolder = holder.clone(&dataBlob);
CFG_ASSERT(baseHolder != nullptr);
}
template<typename RetType, typename ClassType, typename... Args>
CommandHandlerMemFunc(const ClassType * const objPtr, RetType (ClassType::*pMemFunc)(Args...) const)
{
const auto holder = MemFuncHolder<RetType, typename std::add_const<ClassType>::type, Args...>{ objPtr, pMemFunc };
baseHolder = holder.clone(&dataBlob);
CFG_ASSERT(baseHolder != nullptr);
}
template<typename RetType, typename... Args>
RetType invoke(Args&&... args) const
{
CFG_ASSERT(baseHolder != nullptr);
const auto holder = static_cast<const CallableHolder<RetType, Args...> *>(baseHolder);
return holder->invoke(std::forward<Args>(args)...);
}
// nullptr interop:
CommandHandlerMemFunc(std::nullptr_t) noexcept { }
bool operator == (std::nullptr_t) const noexcept { return baseHolder == nullptr; }
bool operator != (std::nullptr_t) const noexcept { return baseHolder != nullptr; }
private:
struct BaseCallableHolder
{
virtual BaseCallableHolder * clone(void * where) const = 0;
virtual ~BaseCallableHolder();
};
template<typename RetType, typename... Args>
struct CallableHolder : BaseCallableHolder
{
virtual RetType invoke(Args&&... args) const = 0;
};
template<typename RetType, typename ClassType, typename... Args>
struct MemFuncHolder final : CallableHolder<RetType, Args...>
{
// This selector will use the const-qualified method if
// ClassType is const, the non-const otherwise.
using MemFunc = RetType (ClassType::*)(Args...);
using CMemFunc = RetType (ClassType::*)(Args...) const;
using MemFuncType = typename std::conditional<std::is_const<ClassType>::value, CMemFunc, MemFunc>::type;
ClassType * objPtr;
MemFuncType pMemFunc;
MemFuncHolder(ClassType * obj, MemFuncType pmf)
: objPtr(obj)
, pMemFunc(pmf)
{
CFG_ASSERT(objPtr != nullptr);
CFG_ASSERT(pMemFunc != nullptr);
}
RetType invoke(Args&&... args) const override
{
return (objPtr->*pMemFunc)(std::forward<Args>(args)...);
}
BaseCallableHolder * clone(void * where) const override
{
// Placement constructed in the external memory buffer.
return ::new(where) MemFuncHolder<RetType, ClassType, Args...>(*this);
}
};
private:
BaseCallableHolder * baseHolder = nullptr;
class Dummy;
using GenericMemFuncHolder = MemFuncHolder<void *, Dummy, void *>;
// MemFuncHolder instances are constructed in-place into this
// buffer, so we don't have to allocate any extra memory for them.
// Visual Studio seems to dislike alignas(), so using a C++11
// unrestricted union instead.
union Blob
{
Blob() { }
~Blob() { }
GenericMemFuncHolder dummy;
std::uint8_t bytes[sizeof(GenericMemFuncHolder)];
};
Blob dataBlob;
};
//
// Use these to create command handlers from a pointer to an
// object and pointer to the member function that will handle
// the command. The member func can optionally be const qualified.
//
// The pointers must not be null.
//
// Example:
// MyClass obj{};
// auto pmf = makeMemFuncCommandHandler(&obj, &MyClass::someMethod);
//
template<typename ClassType>
CommandHandlerMemFunc makeMemFuncCommandHandler(ClassType * objPtr, void (ClassType::*pCmdExec)(const CommandArgs &))
{
return CommandHandlerMemFunc(objPtr, pCmdExec);
}
template<typename ClassType>
CommandHandlerMemFunc makeMemFuncCommandHandler(const ClassType * const objPtr, void (ClassType::*pCmdExec)(const CommandArgs &) const)
{
return CommandHandlerMemFunc(objPtr, pCmdExec);
}
template<typename ClassType>
CommandHandlerMemFunc makeMemFuncCommandArgCompletion(ClassType * objPtr, int (ClassType::*pArgCompl)(const char *, std::string *, int))
{
return CommandHandlerMemFunc(objPtr, pArgCompl);
}
template<typename ClassType>
CommandHandlerMemFunc makeMemFuncCommandArgCompletion(const ClassType * const objPtr, int (ClassType::*pArgCompl)(const char *, std::string *, int) const)
{
return CommandHandlerMemFunc(objPtr, pArgCompl);
}
// ========================================================
// class Command:
// ========================================================
class Command
{
public:
virtual ~Command();
virtual std::uint32_t getFlags() const = 0;
virtual void setFlags(std::uint32_t newFlags) = 0;
virtual const char * getNameCString() const = 0;
virtual const char * getDescCString() const = 0;
virtual std::string getName() const = 0;
virtual std::string getDesc() const = 0;
virtual int getMinArgs() const = 0;
virtual int getMaxArgs() const = 0;
virtual bool isAlias() const = 0;
// Calls the command argument completion callback, if any.
// It will write up to 'maxMatches' in the output array. The returned value is the total
// numbers of matches available (which can be > maxMatches), or -1 if there was an error.
virtual int argumentCompletion(const char * partialArg, std::string * outMatches, int maxMatches) const = 0;
};
// ========================================================
// class CommandManager:
// ========================================================
class CommandManager
{
public:
//
// Allocator/factory:
//
static CommandManager * createInstance(int cmdHashTableSizeHint = 0, CVarManager * cvarMgr = nullptr);
static void destroyInstance(CommandManager * cmdManager);
//
// Constants:
//
// Pass this constant to 'execBufferedCommands()' to indicate
// all the available commands should be processed.
static constexpr std::uint32_t ExecAll = ~0u;
// Pass this constant to 'disableCommandsWithFlags()' to indicate
// all commands, independent of user flags, should be disabled.
// Any further command text input will then be ignored.
static constexpr std::uint32_t DisableAll = ~0u;
//
// CommandManager interface:
//
// Destructor will also destroy all commands registered with this manager.
virtual ~CommandManager();
// Finds previously registered command or returns null if no such command is registered.
virtual Command * findCommand(const char * name) const = 0;
// Find commands with name starting with the 'partialName' substring.
// Returns the total number of matches found, which might be > than maxMatches,
// but only up to maxMatches will be written to the output array in any case.
// Returns a negative value in case of error. Output commands are sorted
// alphabetically according to name.
virtual int findCommandsWithPartialName(const char * partialName,
Command ** outMatches,
int maxMatches) const = 0;
// Same as above, but get only the var names for displaying.
virtual int findCommandsWithPartialName(const char * partialName,
const char ** outMatches,
int maxMatches) const = 0;
// Similar to findCommandsWithPartialName(), but instead searches by commands flags.
virtual int findCommandsWithFlags(std::uint32_t flags,
Command ** outMatches,
int maxMatches) const = 0;
// Remove previously registered command by name or pointer. If this function
// succeeds, all pointers to the command instance will also become invalid!
virtual bool removeCommand(const char * name) = 0;
virtual bool removeCommand(Command * cmd) = 0;
// Removes the command if it is an alias. Fails if the name refers to a normal command.
virtual bool removeCommandAlias(const char * aliasName) = 0;
// Unregisters and deletes all command instances that belong to this manager.
// Be careful when using this method, since all external Command pointers will
// be invalidated. The effect is equivalent to destroying the manager instance.
virtual void removeAllCommands() = 0;
// Unregisters all current command aliases. Normal commands are not touched.
virtual void removeAllCommandAliases() = 0;
// Number of commands registered with this manager so far.
virtual int getRegisteredCommandsCount() const = 0;
// Get just the number of command aliases.
virtual int getCommandAliasCount() const = 0;
// Tests if a string complies with the command naming rules.
// It DOES NOT check if the command is already registered.
virtual bool isValidCommandName(const char * name) const = 0;
// Calls the supplied callback for each registered command.
// No specific iteration order is guaranteed.
virtual void enumerateAllCommands(CommandEnumerateCallback enumCallback, void * userContext) = 0;
// All commands containing any of the specified flags will be
// prevented from executing when processing command text.
// 'DisableAll' prevents all commands from executing.
virtual void disableCommandsWithFlags(std::uint32_t flags) = 0;
// Restores the execution of all commands, regardless of flags.
virtual void enableAllCommands() = 0;
// Set or query the helper CVarManager associated with this CommandManager.
virtual CVarManager * getCVarManager() const = 0;
virtual void setCVarManager(CVarManager * cvarMgr) = 0;
//
// Command registration / command aliases:
//
// Register with C-style function callback handlers.
virtual bool registerCommand(const char * name,
CommandHandlerCallback handler,
CommandArgCompletionCallback completionHandler = nullptr,
void * userContext = nullptr,
const char * description = "",
std::uint32_t flags = 0,
int minArgs = -1,
int maxArgs = -1) = 0;
// Register with delegate handlers (lambdas with possible capture).
virtual bool registerCommand(const char * name,
CommandHandlerDelegate handler,
CommandArgCompletionDelegate completionHandler = nullptr,
const char * description = "",
std::uint32_t flags = 0,
int minArgs = -1,
int maxArgs = -1) = 0;
// Register with pointer-to-member-function handlers.
virtual bool registerCommand(const char * name,
CommandHandlerMemFunc handler,
CommandHandlerMemFunc completionHandler = nullptr,
const char * description = "",
std::uint32_t flags = 0,
int minArgs = -1,
int maxArgs = -1) = 0;
// Create an alias for a command string. Execution mode for
// each time the command alias is invoked can also be provided.
virtual bool createCommandAlias(const char * aliasName,
const char * aliasedCmdStr,
CommandExecMode execMode,
const char * description = "") = 0;
//
// Command text execution:
//
// Executes the given command string immediately.
// Text will not be added to the command buffer.
virtual void execNow(const char * str) = 0;
// Inserts the command text at the front of the command buffer (prepends it).
// Text will not be executed nor validated until a future 'execBufferedCommands()' call.
virtual void execInsert(const char * str) = 0;
// Appends the command text to the end of the command buffer.
// Text will not be executed nor validated until a future 'execBufferedCommands()' call.
virtual void execAppend(const char * str) = 0;
// Execute a command string with any of the available modes.
virtual void execute(CommandExecMode execMode, const char * str) = 0;
// Check if we have pending command text to execute.
virtual bool hasBufferedCommands() const = 0;
// Execute the command buffer text. You can specify a maximum number of commands
// to execute in the call or allow all buffered commands to execute with 'ExecAll'.
// Returns the number of commands executed.
virtual int execBufferedCommands(std::uint32_t maxCommandsToExec = ExecAll) = 0;
// Tries to load and execute the given configuration file.
// Same rules of command strings apply. Lines are assumed to be
// whole commands, unless a CommandTextSeparator (;) is found.
// Commands are executed immediately, so the file contents will
// not go though the command buffer. Errors will not stop the execution
// of the file, only the compromised commands are usually affected.
// If a SimpleCommandTerminal pointer is provided, each executed
// command will also be echoed to that terminal.
virtual bool execConfigFile(const char * filename, SimpleCommandTerminal * term) = 0;
// Process the program command line provided at initialization.
// 'set' and 'reset' commands (modifying CVars) are executed immediately, while
// other commands are buffered and executed when the command buffer is next flushed.
// Setting CVars from the startup command line will allow modifying InitOnly CVars.
//
// '+' characters separate the command line string into multiple commands.
// All of these are valid:
// ./prog +set test blah +foo test
// ./prog set test blah + foo test
//
// Will produce two command lines:
// "set test blah"
// and
// "foo test"
virtual void execStartupCommandLine(int argc, const char * argv[]) = 0;
};
//
// Default commands besides the SimpleCommandTerminal built-ins.
// Includes the common utilities for manipulating CVars and saving
// and loading configuration files. The terminal is the destination
// output of the commands and must be provided. A CommandManager is
// also mandatory. This function becomes a no-op if the defaults are
// disabled at compilation by the 'CFG_NO_DEFAULT_COMMANDS' macro.
//
void registerDefaultCommands(CommandManager * cmdManager, SimpleCommandTerminal * term);
// ================================================================================================
//
// Interactive Terminal/Console
//
// ================================================================================================
// ========================================================
// Special keys for console keyboard input:
// ========================================================
struct SpecialKeys final
{
enum
{
Return = 1 << 8,
Tab = 1 << 9,
Backspace = 1 << 10,
Delete = 1 << 11,
UpArrow = 1 << 12,
DownArrow = 1 << 13,
RightArrow = 1 << 14,
LeftArrow = 1 << 15,
Escape = 1 << 16,
Control = 1 << 17
// Other keys use the equivalent ASCII character,
// so these constants skip the first 8bits.
};
static std::string toString(int key);
};
// ========================================================
// class SimpleCommandTerminal:
// ========================================================
//
// This class is a base with the common operations for line input
// and printing. You never directly instantiate one of these, instead
// you can use the provided NativeTerminal implementations or extend
// this base class to implement other custom GUI terminals/consoles.
//
class SimpleCommandTerminal
{
public:
//
// Command Terminal interface:
//
// Not copyable.
SimpleCommandTerminal(const SimpleCommandTerminal &) = delete;
SimpleCommandTerminal & operator = (const SimpleCommandTerminal &) = delete;
virtual ~SimpleCommandTerminal();
// 'newlineMark' is the character(s) printed at the start of every new input line.
// The managers are optional and may be null. If a manager is null, that functionality is disabled.
SimpleCommandTerminal(CommandManager * cmdMgr = nullptr,
CVarManager * cvarMgr = nullptr,
const char * newlineMark = "> ");
// Prints an ASCII string to the console.
virtual void print(const char * text) = 0;
// Similar to print() but appends a newline by default.
virtual void printLn(const char * text) = 0;
// Printf-style text printing. No default newline appended.
// The default implementation provided relies on the 'print()' method.
virtual void printF(const char * fmt, ...) CFG_PRINTF_FUNC(2, 3);
// Pushes a character into the line input buffer or handles a special key.
// Returns true if the key event was handled, false if it was ignored.
virtual bool handleKeyInput(int key, char chr);
// Clears the terminal's screen.
// Note: Be sure to call it even if overridden in a derived class.
virtual void clear();
// Call update after running a batch of commands with the CommandManager that is
// associated to this terminal. This will make sure the newline marker is drawn.
virtual void update();
// Color printing:
void setTextColor(const char * ansiColorCode) noexcept;
void restoreTextColor() noexcept;
//
// Command/CVar managers:
// (The terminal will not take ownership of the pointers).
//
CommandManager * getCommandManager() const noexcept;
CommandExecMode getCommandExecMode() const noexcept;
CVarManager * getCVarManager() const noexcept;
void setCommandManager(CommandManager * cmdMgr) noexcept;
void setCommandExecMode(CommandExecMode newMode) noexcept;
void setCVarManager(CVarManager * cvarMgr) noexcept;
//
// Command history for the current session: