-
Notifications
You must be signed in to change notification settings - Fork 47
/
ScriptingSystem.cpp
505 lines (404 loc) · 14.5 KB
/
ScriptingSystem.cpp
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
#include "ScriptingSystem.h"
#include "i18n.h"
#include "itextstream.h"
#include "iradiant.h"
#include "ieventmanager.h"
#include "iuimanager.h"
#include "imainframe.h"
#include "igroupdialog.h"
#include "interfaces/MathInterface.h"
#include "interfaces/RegistryInterface.h"
#include "interfaces/RadiantInterface.h"
#include "interfaces/SceneGraphInterface.h"
#include "interfaces/EClassInterface.h"
#include "interfaces/SelectionInterface.h"
#include "interfaces/BrushInterface.h"
#include "interfaces/PatchInterface.h"
#include "interfaces/EntityInterface.h"
#include "interfaces/MapInterface.h"
#include "interfaces/CommandSystemInterface.h"
#include "interfaces/GameInterface.h"
#include "interfaces/FileSystemInterface.h"
#include "interfaces/GridInterface.h"
#include "interfaces/ShaderSystemInterface.h"
#include "interfaces/ModelInterface.h"
#include "interfaces/SkinInterface.h"
#include "interfaces/SoundInterface.h"
#include "interfaces/DialogInterface.h"
#include "interfaces/SelectionSetInterface.h"
#include "ScriptWindow.h"
#include "SceneNodeBuffer.h"
#include <wx/frame.h>
#include "os/fs.h"
#include "os/file.h"
#include "os/path.h"
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
namespace script {
ScriptingSystem::ScriptingSystem() :
_outputWriter(false, _outputBuffer),
_errorWriter(true, _errorBuffer),
_initialised(false)
{}
void ScriptingSystem::addInterface(const std::string& name, const IScriptInterfacePtr& iface) {
// Check if exists
if (interfaceExists(name)) {
rError() << "Cannot add script interface " << name
<< ", this interface is already registered." << std::endl;
return;
}
// Try to insert
_interfaces.push_back(NamedInterface(name, iface));
if (_initialised) {
// Add the interface at once, all the others are already added
iface->registerInterface(_mainObjects->mainNamespace);
}
}
bool ScriptingSystem::interfaceExists(const std::string& name) {
// Traverse the interface list
for (Interfaces::iterator i = _interfaces.begin(); i != _interfaces.end(); ++i) {
if (i->first == name) {
return true;
}
}
return false;
}
void ScriptingSystem::executeScriptFile(const std::string& filename) {
try
{
std::string filePath = _scriptPath + filename;
// Prevent calling exec_file with a non-existent file, we would
// get crashes during Py_Finalize later on.
if (!os::fileOrDirExists(filePath))
{
rError() << "Error: File " << filePath << " doesn't exist." << std::endl;
return;
}
// Attempt to run the specified script
boost::python::object ignored = boost::python::exec_file(
filePath.c_str(),
_mainObjects->mainNamespace,
_mainObjects->globals
);
}
catch (std::invalid_argument& e) // thrown when the file doesn't exist
{
rError() << "Error trying to execute file " << filename << ": " << e.what() << std::endl;
}
catch (const boost::python::error_already_set&) {
rError() << "Error while executing file: "
<< filename << ": " << std::endl;
// Dump the error to the console, this will invoke the PythonConsoleWriter
PyErr_Print();
PyErr_Clear();
// Python is usually not appending line feeds...
rMessage() << std::endl;
}
}
ExecutionResultPtr ScriptingSystem::executeString(const std::string& scriptString)
{
ExecutionResultPtr result(new ExecutionResult);
result->errorOccurred = false;
// Clear the output buffers before starting to execute
_outputBuffer.clear();
_errorBuffer.clear();
try
{
// Attempt to run the specified script
boost::python::object ignored = boost::python::exec(
scriptString.c_str(),
_mainObjects->mainNamespace,
_mainObjects->globals
);
}
catch (const boost::python::error_already_set&)
{
result->errorOccurred = true;
// Dump the error to the console, this will invoke the PythonConsoleWriter
PyErr_Print();
PyErr_Clear();
}
result->output += _outputBuffer + "\n";
result->output += _errorBuffer + "\n";
_outputBuffer.clear();
_errorBuffer.clear();
return result;
}
void ScriptingSystem::initialise()
{
// Add the registered interfaces
try {
for (Interfaces::iterator i = _interfaces.begin(); i != _interfaces.end(); ++i) {
// Handle each interface in its own try/catch block
try
{
i->second->registerInterface(_mainObjects->mainNamespace);
}
catch (const boost::python::error_already_set&)
{
rError() << "Error while initialising interface "
<< i->first << ": " << std::endl;
PyErr_Print();
PyErr_Clear();
rMessage() << std::endl;
}
}
}
catch (const boost::python::error_already_set&) {
// Dump the error to the console, this will invoke the PythonConsoleWriter
PyErr_Print();
PyErr_Clear();
// Python is usually not appending line feeds...
rMessage() << std::endl;
}
_initialised = true;
// Start the init script
executeScriptFile("init.py");
// Add the scripting widget to the groupdialog
IGroupDialog::PagePtr page(new IGroupDialog::Page);
page->name = "ScriptWindow";
page->windowLabel = _("Script");
page->page = new ScriptWindow(GlobalMainFrame().getWxTopLevelWindow());
page->tabIcon = "icon_script.png";
page->tabLabel = _("Script");
page->position = IGroupDialog::Page::Position::Console - 10; // insert before console
GlobalGroupDialog().addPage(page);
}
void ScriptingSystem::runScriptFile(const cmd::ArgumentList& args) {
// Start the test script
if (args.empty()) return;
executeScriptFile(args[0].getString());
}
void ScriptingSystem::runScriptCommand(const cmd::ArgumentList& args) {
// Start the test script
if (args.empty()) return;
executeCommand(args[0].getString());
}
void ScriptingSystem::reloadScriptsCmd(const cmd::ArgumentList& args) {
reloadScripts();
}
void ScriptingSystem::executeCommand(const std::string& name) {
// Sanity check
if (!_initialised) {
rError() << "Cannot execute script command " << name
<< ", ScriptingSystem not initialised yet." << std::endl;
return;
}
// Lookup the name
ScriptCommandMap::iterator found = _commands.find(name);
if (found == _commands.end()) {
rError() << "Couldn't find command " << name << std::endl;
return;
}
// Set the execution flag in the global namespace
_mainObjects->globals["__executeCommand__"] = true;
// Execute the script file behind this command
executeScriptFile(found->second->getFilename());
}
void ScriptingSystem::loadCommandScript(const std::string& scriptFilename)
{
try
{
// Create a new dictionary for the initialisation routine
boost::python::dict locals;
// Disable the flag for initialisation, just for sure
locals["__executeCommand__"] = false;
// Attempt to run the specified script
boost::python::object ignored = boost::python::exec_file(
(_scriptPath + scriptFilename).c_str(),
_mainObjects->mainNamespace,
locals // pass the new dictionary for the locals
);
std::string cmdName;
std::string cmdDisplayName;
if (locals.has_key("__commandName__"))
{
cmdName = boost::python::extract<std::string>(locals["__commandName__"]);
}
if (locals.has_key("__commandDisplayName__"))
{
cmdDisplayName = boost::python::extract<std::string>(locals["__commandDisplayName__"]);
}
if (!cmdName.empty())
{
if (cmdDisplayName.empty())
{
cmdDisplayName = cmdName;
}
// Successfully retrieved the command
ScriptCommandPtr cmd(new ScriptCommand(cmdName, cmdDisplayName, scriptFilename));
// Try to register this named command
std::pair<ScriptCommandMap::iterator, bool> result = _commands.insert(
ScriptCommandMap::value_type(cmdName, cmd)
);
// Result.second is TRUE if the insert succeeded
if (result.second) {
rMessage() << "Registered script file " << scriptFilename
<< " as " << cmdName << std::endl;
}
else {
rError() << "Error in " << scriptFilename << ": Script command "
<< cmdName << " has already been registered in "
<< _commands[cmdName]->getFilename() << std::endl;
}
}
}
catch (const boost::python::error_already_set&) {
rError() << "Script file " << scriptFilename
<< " is not a valid command." << std::endl;
// Dump the error to the console, this will invoke the PythonConsoleWriter
PyErr_Print();
PyErr_Clear();
// Python is usually not appending line feeds...
rMessage() << std::endl;
}
}
void ScriptingSystem::reloadScripts()
{
// Release all previously allocated commands
_commands.clear();
// Initialise the search's starting point
fs::path start = fs::path(_scriptPath) / "commands/";
if (!fs::exists(start)) {
rWarning() << "Couldn't find scripts folder: " << start.string() << std::endl;
return;
}
for (fs::recursive_directory_iterator it(start);
it != fs::recursive_directory_iterator(); ++it)
{
// Get the candidate
const fs::path& candidate = *it;
if (fs::is_directory(candidate)) continue;
std::string extension = os::getExtension(candidate.string());
boost::algorithm::to_lower(extension);
if (extension != "py") continue;
// Script file found, construct a new command
loadCommandScript(os::getRelativePath(candidate.generic_string(), _scriptPath));
}
rMessage() << "ScriptModule: Found " << _commands.size() << " commands." << std::endl;
// Re-create the script menu
_scriptMenu.reset();
_scriptMenu = ui::ScriptMenuPtr(new ui::ScriptMenu(_commands));
}
// RegisterableModule implementation
const std::string& ScriptingSystem::getName() const
{
static std::string _name(MODULE_SCRIPTING_SYSTEM);
return _name;
}
const StringSet& ScriptingSystem::getDependencies() const {
static StringSet _dependencies;
if (_dependencies.empty()) {
_dependencies.insert(MODULE_RADIANT);
_dependencies.insert(MODULE_COMMANDSYSTEM);
_dependencies.insert(MODULE_UIMANAGER);
_dependencies.insert(MODULE_EVENTMANAGER);
}
return _dependencies;
}
void ScriptingSystem::initialiseModule(const ApplicationContext& ctx)
{
rMessage() << getName() << "::initialiseModule called." << std::endl;
// Subscribe to get notified as soon as Radiant is fully initialised
GlobalRadiant().signal_radiantStarted().connect(
sigc::mem_fun(this, &ScriptingSystem::initialise)
);
// Construct the script path
#if defined(POSIX) && defined(PKGLIBDIR)
_scriptPath = std::string(PKGLIBDIR) + "/scripts/";
#else
_scriptPath = ctx.getRuntimeDataPath() + "scripts/";
#endif
// start the python interpreter
Py_Initialize();
rMessage() << getName() << ": Python interpreter initialised." << std::endl;
// Initialise the boost::python objects
_mainObjects.reset(new BoostPythonMainObjects);
_mainObjects->mainModule = boost::python::import("__main__");
_mainObjects->mainNamespace = _mainObjects->mainModule.attr("__dict__");
try {
// Construct the console writer interface
PythonConsoleWriterClass consoleWriter("PythonConsoleWriter", boost::python::init<bool, std::string&>());
consoleWriter.def("write", &PythonConsoleWriter::write);
// Declare the interface to python
_mainObjects->mainNamespace["PythonConsoleWriter"] = consoleWriter;
// Redirect stdio output to our local ConsoleWriter instances
boost::python::import("sys").attr("stderr") = boost::python::ptr(&_errorWriter);
boost::python::import("sys").attr("stdout") = boost::python::ptr(&_outputWriter);
}
catch (const boost::python::error_already_set&) {
// Dump the error to the console, this will invoke the PythonConsoleWriter
PyErr_Print();
PyErr_Clear();
// Python is usually not appending line feeds...
rMessage() << std::endl;
}
// Declare the std::vector<std::string> object to Python, this is used several times
_mainObjects->mainNamespace["StringVector"] = boost::python::class_< std::vector<std::string> >("StringVector")
.def(boost::python::vector_indexing_suite<std::vector<std::string>, true>())
;
// Add the built-in interfaces (the order is important, as we don't have dependency-resolution yet)
addInterface("Math", MathInterfacePtr(new MathInterface));
addInterface("GameManager", GameInterfacePtr(new GameInterface));
addInterface("CommandSystem", CommandSystemInterfacePtr(new CommandSystemInterface));
addInterface("SceneGraph", SceneGraphInterfacePtr(new SceneGraphInterface));
addInterface("GlobalRegistry", RegistryInterfacePtr(new RegistryInterface));
addInterface("GlobalEntityClassManager", EClassManagerInterfacePtr(new EClassManagerInterface));
addInterface("GlobalSelectionSystem", SelectionInterfacePtr(new SelectionInterface));
addInterface("Brush", BrushInterfacePtr(new BrushInterface));
addInterface("Patch", PatchInterfacePtr(new PatchInterface));
addInterface("Entity", EntityInterfacePtr(new EntityInterface));
addInterface("Radiant", RadiantInterfacePtr(new RadiantInterface));
addInterface("Map", MapInterfacePtr(new MapInterface));
addInterface("FileSystem", FileSystemInterfacePtr(new FileSystemInterface));
addInterface("Grid", GridInterfacePtr(new GridInterface));
addInterface("ShaderSystem", ShaderSystemInterfacePtr(new ShaderSystemInterface));
addInterface("Model", ModelInterfacePtr(new ModelInterface));
addInterface("ModelSkinCacheInterface", ModelSkinCacheInterfacePtr(new ModelSkinCacheInterface));
addInterface("SoundManager", SoundManagerInterfacePtr(new SoundManagerInterface));
addInterface("DialogInterface", DialogManagerInterfacePtr(new DialogManagerInterface));
addInterface("SelectionSetInterface", SelectionSetInterfacePtr(new SelectionSetInterface));
GlobalCommandSystem().addCommand(
"RunScript",
boost::bind(&ScriptingSystem::runScriptFile, this, _1),
cmd::ARGTYPE_STRING
);
GlobalCommandSystem().addCommand(
"ReloadScripts",
boost::bind(&ScriptingSystem::reloadScriptsCmd, this, _1)
);
GlobalCommandSystem().addCommand(
"RunScriptCommand",
boost::bind(&ScriptingSystem::runScriptCommand, this, _1),
cmd::ARGTYPE_STRING
);
// Search script folder for commands
reloadScripts();
// Bind the reloadscripts command to the menu
GlobalEventManager().addCommand("ReloadScripts", "ReloadScripts");
// Add the menu item
IMenuManager& mm = GlobalUIManager().getMenuManager();
mm.insert("main/file/refreshShaders", // menu location path
"ReloadScripts", // name
ui::menuItem, // type
_("Reload Scripts"), // caption
"", // icon
"ReloadScripts"); // event name
SceneNodeBuffer::Instance().clear();
}
void ScriptingSystem::shutdownModule()
{
rMessage() << getName() << "::shutdownModule called." << std::endl;
_scriptMenu = ui::ScriptMenuPtr();
// Clear the buffer so that nodes finally get destructed
SceneNodeBuffer::Instance().clear();
_commands.clear();
_scriptPath.clear();
// Free all interfaces
_interfaces.clear();
_initialised = false;
// Clear the boost::python::objects
_mainObjects.reset();
Py_Finalize();
}
} // namespace script