Debian Codegraph @

include/icommandsystem.h

raw
1 #pragma once
2
3 #include <memory>
4 #include <functional>
5 #include "math/Vector2.h"
6 #include "math/Vector3.h"
7
8 #include "imodule.h"
9
10 #include "string/convert.h"
11
12 namespace cmd
13 {
14
15 // Use these to define argument types
16 enum ArgumentTypeFlags
17 {
18 ARGTYPE_VOID = 0,
19 ARGTYPE_STRING = 1 << 0,
20 ARGTYPE_INT = 1 << 1,
21 ARGTYPE_DOUBLE = 1 << 2,
22 ARGTYPE_VECTOR3 = 1 << 3,
23 ARGTYPE_VECTOR2 = 1 << 4,
24 // future types go here
25 ARGTYPE_OPTIONAL = 1 << 16,
26 };
27
28 /**
29 * @brief A single command argument which may be of several different types.
30 *
31 * The argument maintains a list of type flags which indicate which types this argument may be
32 * interpreted as. For example, an argument constructed from an integer may also be interpreted as
33 * a double, so will have both ARGTYPE_INT and ARGTYPE_DOUBLE.
34 */
35 class Argument
36 {
37 std::string _strValue;
38 double _doubleValue;
39 int _intValue;
40 Vector3 _vector3Value;
41 Vector2 _vector2Value;
42
43 // The type flags
44 std::size_t _type;
45
46 public:
47 Argument() :
48 _doubleValue(0),
49 _intValue(0),
50 _vector3Value(0,0,0),
51 _vector2Value(0,0),
52 _type(ARGTYPE_VOID)
53 {}
54
55 // String => Argument constructor
56 Argument(const std::string& str) :
57 _strValue(str),
58 _doubleValue(string::convert<double>(str)),
59 _intValue(string::convert<int>(str)),
60 _vector3Value(string::convert<Vector3>(str)),
61 _vector2Value(Vector2(str)),
62 _type(ARGTYPE_STRING)
63 {
64 tryNumberConversion();
65 tryVectorConversion();
66 }
67
68 // Double => Argument constructor
69 Argument(const double d) :
70 _strValue(string::to_string(d)),
71 _doubleValue(d),
72 _intValue(static_cast<int>(d)),
73 _vector3Value(d,d,d),
74 _vector2Value(d,d),
75 _type(ARGTYPE_DOUBLE)
76 {
77 // Enable INT flag if double value is rounded
78 if (lrint(_doubleValue) == _intValue) {
79 _type |= ARGTYPE_INT;
80 }
81 }
82
83 // Int => Argument constructor
84 Argument(const int i) :
85 _strValue(string::to_string(i)),
86 _doubleValue(static_cast<double>(i)),
87 _intValue(i),
88 _vector3Value(i,i,i),
89 _vector2Value(i,i),
90 _type(ARGTYPE_INT|ARGTYPE_DOUBLE) // INT can be used as DOUBLE too
91 {}
92
93 // Vector3 => Argument constructor
94 Argument(const Vector3& v) :
95 _strValue(string::to_string(v[0]) + " " + string::to_string(v[1]) + " " + string::to_string(v[2])),
96 _doubleValue(v.getLength()),
97 _intValue(static_cast<int>(v.getLength())),
98 _vector3Value(v),
99 _vector2Value(v[0], v[1]),
100 _type(ARGTYPE_VECTOR3)
101 {}
102
103 // Vector2 => Argument constructor
104 Argument(const Vector2& v) :
105 _strValue(string::to_string(v[0]) + " " + string::to_string(v[1]) + " " + string::to_string(v[2])),
106 _doubleValue(v.getLength()),
107 _intValue(static_cast<int>(v.getLength())),
108 _vector3Value(v[0], v[1], 0),
109 _vector2Value(v),
110 _type(ARGTYPE_VECTOR2)
111 {}
112
113 // Copy Constructor
114 Argument(const Argument& other) :
115 _strValue(other._strValue),
116 _doubleValue(other._doubleValue),
117 _intValue(other._intValue),
118 _vector3Value(other._vector3Value),
119 _vector2Value(other._vector2Value),
120 _type(other._type)
121 {}
122
123 std::size_t getType() const
124 {
125 return _type;
126 }
127
128 std::string getString() const
129 {
130 return _strValue;
131 }
132
133 bool getBoolean() const
134 {
135 return getInt() != 0;
136 }
137
138 int getInt() const
139 {
140 return _intValue;
141 }
142
143 double getDouble() const
144 {
145 return _doubleValue;
146 }
147
148 Vector3 getVector3() const
149 {
150 return _vector3Value;
151 }
152
153 Vector2 getVector2() const
154 {
155 return _vector2Value;
156 }
157
158 private:
159 void tryNumberConversion()
160 {
161 // Try to cast the string value to numbers
162 try {
163 _intValue = std::stoi(_strValue);
164 // cast succeeded
165 _type |= ARGTYPE_INT;
166 }
167 catch (std::logic_error&) {}
168
169 try
170 {
171 _doubleValue = std::stod(_strValue);
172 // cast succeeded
173 _type |= ARGTYPE_DOUBLE;
174 }
175 catch (std::invalid_argument&) {}
176 }
177
178 void tryVectorConversion()
179 {
180 // Use a stringstream to parse the string
181 std::stringstream strm(_strValue);
182 strm << std::skipws;
183
184 // Try converting the first two values
185 strm >> _vector2Value.x();
186 strm >> _vector2Value.y();
187
188 if (!strm.fail()) {
189 _type |= ARGTYPE_VECTOR2;
190
191 // Try to parse the third value
192 strm >> _vector3Value.z();
193
194 if (!strm.fail()) {
195 // Third value successfully parsed
196 _type |= ARGTYPE_VECTOR3;
197 // Copy the two values from the parsed Vector2
198 _vector3Value.x() = _vector2Value.x();
199 _vector3Value.y() = _vector2Value.y();
200 }
201 }
202 }
203 };
204
205 typedef std::vector<Argument> ArgumentList;
206
207 /**
208 * greebo: A command target must take an ArgumentList argument, like this:
209 *
210 * void doSomething(const ArgumentList& args);
211 *
212 * This can be both a free function and a member function.
213 */
214 typedef std::function<void (const ArgumentList&)> Function;
215
216 /// Convert a zero-argument function into a Function by discarding the ArgumentList
217 template <typename F> Function noArgs(F f)
218 {
219 return [f](const ArgumentList&) { f(); };
220 }
221
222 /**
223 * @brief Signature for a function which can test if a particular command should
224 * be enabled.
225 */
226 using CheckFunction = std::function<bool()>;
227
228 // A command signature consists just of arguments, return type is always void
229 typedef std::vector<std::size_t> Signature;
230
231 /**
232 * greebo: Auto-completion information returned by the CommandSystem
233 * when the user is entering a partial command.
234 */
235 struct AutoCompletionInfo
236 {
237 // The command prefix this info is referring to
238 std::string prefix;
239
240 // The candidaes, alphabetically ordered, case-insensitively
241 typedef std::vector<std::string> Candidates;
242 Candidates candidates;
243 };
244
245 /**
246 * @brief Interface for the CommandSystem module.
247 *
248 * Commands are self-contained blocks of code (function calls or lambdas) which
249 * can be invoked from menu items or from typing string commands in the
250 * DarkRadiant console. They can also be called from Python.
251 *
252 * Commands can be invoked programmatically via the executeCommand() method,
253 * which is sometimes useful if the implementing function isn't exposed via a
254 * suitable module interface. Note however that neither the name of the command
255 * (an arbitrary string) or the types of its arguments are checked at
256 * compile-time, so calling C++ methods directly is generally preferable where
257 * possible.
258 */
259 class ICommandSystem: public RegisterableModule
260 {
261 public:
262
263 /**
264 * Visit each command/bind using the given lambda. The functor is going to be called
265 * with the command name as argument.
266 */
267 virtual void foreachCommand(const std::function<void(const std::string&)>& functor) = 0;
268
269 /**
270 * greebo: Declares a new command with the given signature.
271 */
272 virtual void addCommand(const std::string& name, Function func,
273 const Signature& signature = Signature()) = 0;
274
275 /**
276 * @brief Add a new command with a check function which can test if the
277 * command is currently runnable.
278 *
279 * This is aimed at commands which are not always available, e.g. because
280 * they require one or more objects to be selected. If the command is not
281 * currently available, the UI might choose to disable the button or menu
282 * item which invokes it.
283 *
284 * @param name
285 * Name of the command.
286 *
287 * @param func
288 * Function to call when the command is invoked.
289 *
290 * @param check
291 * Function to check whether the command should be enabled based on current
292 * application state.
293 */
294 virtual void addWithCheck(const std::string& name, Function func, CheckFunction check,
295 const Signature& = {}) = 0;
296
297 /// Returns true if the named command exists
298 virtual bool commandExists(const std::string& name) = 0;
299
300 /**
301 * @brief Check if the named command is currently runnable.
302 *
303 * This is just a signal to the UI that a command should be disabled; the
304 * command system does NOT guarantee that a command for which canExecute()
305 * returns false won't actually be invoked by a subsequent call to
306 * executeCommand().
307 */
308 virtual bool canExecute(const std::string& name) const = 0;
309
310 /**
311 * Remove a named command.
312 */
313 virtual void removeCommand(const std::string& name) = 0;
314
315 /**
316 * greebo: Define a new statement, which consists of a name and a
317 * string to execute.
318 *
319 * Consider this as some sort of macro.
320 *
321 * @statementName: The name of the statement, e.g. "exportASE"
322 * @string: The string to execute.
323 * @saveStatementToRegistry: when TRUE (default) this statement/bind
324 * is saved to the registry at program shutdown. Pass FALSE if you
325 * don't want to let this statement persist between sessions.
326 */
327 virtual void addStatement(const std::string& statementName,
328 const std::string& string,
329 bool saveStatementToRegistry = true) = 0;
330
331 /**
332 * Visit each statement (bind) using the given lambda. The functor is going to be called
333 * with the statement name as argument.
334 */
335 virtual void foreachStatement(const std::function<void(const std::string&)>& functor, bool customStatementsOnly = false) = 0;
336
337 /**
338 * Returns the signature for the named command or bind. Statements
339 * always have an empty signature.
340 */
341 virtual Signature getSignature(const std::string& name) = 0;
342
343 /**
344 * greebo: Executes the given string as if the user had typed it
345 * in the command console. The passed string can be a sequence of
346 * statements separated by semicolon ';' characters. Each statement
347 * can have zero or more arguments, separated by spaces.
348 *
349 * It is possible to pass string arguments by using
350 * double- or single-quote characters.
351 * e.g. "This; string; will be; treated as a whole".
352 *
353 * The last command needs not to be delimited by a semicolon.
354 *
355 * Example: nudgeLeft; nudgeRight -1 0 0; write "Bla! Test"
356 */
357 virtual void execute(const std::string& input) = 0;
358
359 /// Execute the named command with the given list of arguments
360 virtual void executeCommand(const std::string& name, const ArgumentList& args = {}) = 0;
361
362 /// Convenience method to execute a command with 1 argument
363 void executeCommand(const std::string& name, const Argument& arg1)
364 {
365 executeCommand(name, ArgumentList{arg1});
366 }
367
368 /// Convenience method to execute a command with 2 arguments
369 void executeCommand(const std::string& name, const Argument& arg1, const Argument& arg2)
370 {
371 executeCommand(name, {arg1, arg2});
372 }
373
374 /**
375 * greebo: Returns autocompletion info for the given prefix.
376 */
377 virtual AutoCompletionInfo getAutoCompletionInfo(const std::string& prefix) = 0;
378 };
379 typedef std::shared_ptr<ICommandSystem> ICommandSystemPtr;
380
381 } // namespace cmd
382
383 const char* const MODULE_COMMANDSYSTEM("CommandSystem");
384
385 // This is the accessor for the commandsystem
386 inline cmd::ICommandSystem& GlobalCommandSystem()
387 {
388 static module::InstanceReference<cmd::ICommandSystem> _reference(MODULE_COMMANDSYSTEM);
389 return _reference;
390 }