Debian Codegraph @

plugins/script/PythonModule.cpp

raw
1 #include "PythonModule.h"
2
3 // Stringify and concatenate the PYBIND11_VERSION_xxx preprocessor symbols
4 #define Str(x) #x
5 #define QUOTE(x) Str(x)
6 #define PYBIND11_VERSION_STR (QUOTE(PYBIND11_VERSION_MAJOR) "." QUOTE(PYBIND11_VERSION_MINOR) "." QUOTE(PYBIND11_VERSION_PATCH))
7
8 #include <pybind11/embed.h>
9 #include <pybind11/stl_bind.h>
10 #include <pybind11/attr.h>
11 #include <pybind11/eval.h>
12
13 #include "itextstream.h"
14 #include "os/file.h"
15 #include "os/path.h"
16
17 namespace script
18 {
19
20 namespace
21 {
22 constexpr const char* ModuleName = "darkradiant";
23 }
24
25 PythonModule::PythonModule() :
26 _outputWriter(false, _outputBuffer),
27 _errorWriter(true, _errorBuffer),
28 _interpreterInitialised(false)
29 {
30 registerModule();
31 }
32
33 PythonModule::~PythonModule()
34 {
35 _namedInterfaces.clear();
36
37 // Release the references to trigger the internal cleanup before Py_Finalize
38 _module.dec_ref();
39 _module.release();
40
41 _globals.reset();
42
43 py::finalize_interpreter();
44
45 // The memory allocated to initialise the module_def structure
46 // needs to stay alive until the interpreter is finalised
47 _moduleDef.reset();
48 }
49
50 void PythonModule::initialise()
51 {
52 py::initialize_interpreter();
53
54 try
55 {
56 // Import the darkradiant module
57 // This is triggering the call to InitModule as passed to the inittab
58 // so we need to set the static _instance pointer right before and clear it afterwards
59 _instance = this;
60
61 py::module::import(ModuleName);
62
63 // Construct the console writer interface
64 PythonConsoleWriterClass consoleWriter(_module, "PythonConsoleWriter");
65 consoleWriter.def(py::init<bool, std::string&>());
66 consoleWriter.def("write", &PythonConsoleWriter::write);
67 consoleWriter.def("flush", &PythonConsoleWriter::flush);
68
69 // Redirect stdio output to our local ConsoleWriter instances
70 py::module::import("sys").attr("stderr") = &_errorWriter;
71 py::module::import("sys").attr("stdout") = &_outputWriter;
72
73 // String vector is used in multiple places
74 py::bind_vector< std::vector<std::string> >(_module, "StringVector");
75 }
76 catch (const py::error_already_set& ex)
77 {
78 rError() << ex.what() << std::endl;
79 }
80
81 // Not needed anymore
82 _instance = nullptr;
83 }
84
85 void PythonModule::registerModule()
86 {
87 rMessage() << "Registering darkradiant module to Python using pybind11 version " <<
88 PYBIND11_VERSION_STR << std::endl;
89
90 // Register the darkradiant module to Python, the InitModule function
91 // will be called as soon as the module is imported
92 int result = PyImport_AppendInittab(ModuleName, InitModule);
93
94 if (result == -1)
95 {
96 rError() << "Could not initialise Python module" << std::endl;
97 return;
98 }
99 }
100
101 ExecutionResultPtr PythonModule::executeString(const std::string& scriptString)
102 {
103 ExecutionResultPtr result = std::make_shared<ExecutionResult>();
104
105 result->errorOccurred = false;
106
107 // Clear the output buffers before starting to execute
108 _outputBuffer.clear();
109 _errorBuffer.clear();
110
111 try
112 {
113 std::string fullScript = "import " + std::string(ModuleName) + " as DR\n"
114 "from " + std::string(ModuleName) + " import *\n";
115 fullScript.append(scriptString);
116
117 // Attempt to run the specified script
118 py::eval<py::eval_statements>(fullScript, getGlobals());
119 }
120 catch (py::error_already_set& ex)
121 {
122 _errorBuffer.append(ex.what());
123 result->errorOccurred = true;
124
125 rError() << "Error executing script: " << ex.what() << std::endl;
126 }
127
128 result->output += _outputBuffer + "\n";
129 result->output += _errorBuffer + "\n";
130
131 _outputBuffer.clear();
132 _errorBuffer.clear();
133
134 return result;
135 }
136
137 void PythonModule::executeScriptFile(const std::string& scriptBasePath, const std::string& relativeScriptPath, bool setExecuteCommandAttr)
138 {
139 try
140 {
141 auto fullPath = scriptBasePath + relativeScriptPath;
142
143 // Prevent calling exec_file with a non-existent file, we would
144 // get crashes during Py_Finalize later on.
145 if (!os::fileOrDirExists(fullPath))
146 {
147 rError() << "Error: File " << fullPath << " doesn't exist." << std::endl;
148 return;
149 }
150
151 py::dict locals;
152
153 if (setExecuteCommandAttr)
154 {
155 locals["__executeCommand__"] = true;
156 }
157
158 // Attempt to run the specified script
159 py::eval_file(fullPath, getGlobals(), locals);
160 }
161 catch (std::invalid_argument& e)
162 {
163 rError() << "Error trying to execute file " << relativeScriptPath << ": " << e.what() << std::endl;
164 }
165 catch (const py::error_already_set& ex)
166 {
167 rError() << "Error while executing file: " << relativeScriptPath << ": " << std::endl;
168 rError() << ex.what() << std::endl;
169 }
170 }
171
172 py::dict& PythonModule::getGlobals()
173 {
174 if (!_globals)
175 {
176 _globals.reset(new py::dict);
177 }
178
179 return *_globals;
180 }
181
182 #if PY_MAJOR_VERSION >= 3
183 PyObject* PythonModule::InitModule()
184 {
185 if (!_instance) throw new std::runtime_error("_instance reference not set");
186 return _instance->initialiseModule();
187 }
188 #else
189 void PythonModule::InitModule()
190 {
191 if (!_instance) throw new std::runtime_error("_instance reference not set");
192 _instance->initialiseModule();
193 }
194 #endif
195
196 PyObject* PythonModule::initialiseModule()
197 {
198 try
199 {
200 _moduleDef = std::make_unique<py::module::module_def>();
201 _module = py::module::create_extension_module(ModuleName, "DarkRadiant Main Module", _moduleDef.get());
202
203 // Add the registered interfaces
204 for (const auto& i : _namedInterfaces)
205 {
206 // Handle each interface in its own try/catch block
207 try
208 {
209 i.second->registerInterface(_module, getGlobals());
210 }
211 catch (const py::error_already_set& ex)
212 {
213 rError() << "Error while initialising interface " << i.first << ": " << std::endl;
214 rError() << ex.what() << std::endl;
215 }
216 }
217
218 auto main = py::module::import("__main__");
219 auto globals = main.attr("__dict__").cast<py::dict>();
220
221 for (auto i = globals.begin(); i != globals.end(); ++i)
222 {
223 getGlobals()[(*i).first] = (*i).second;
224 }
225
226 _interpreterInitialised = true;
227
228 return _module.ptr();
229 }
230 catch (py::error_already_set& e)
231 {
232 //e.clear();
233 PyErr_SetString(PyExc_ImportError, e.what());
234 return nullptr;
235 }
236 catch (const std::exception& e)
237 {
238 PyErr_SetString(PyExc_ImportError, e.what());
239 return nullptr;
240 }
241 }
242
243 void PythonModule::addInterface(const NamedInterface& iface)
244 {
245 // Check if exists
246 if (interfaceExists(iface.first))
247 {
248 rError() << "A script interface with the name " << iface.first << " is already registered." << std::endl;
249 return;
250 }
251
252 // Add to the list to hold the reference
253 _namedInterfaces.emplace_back(iface);
254
255 // Initialise the interface at once, if the module is already alive
256 if (_interpreterInitialised)
257 {
258 iface.second->registerInterface(_module, getGlobals());
259 }
260 }
261
262 bool PythonModule::interfaceExists(const std::string& name)
263 {
264 // Traverse the interface list
265 for (const auto& namedInterface : _namedInterfaces)
266 {
267 if (namedInterface.first == name)
268 {
269 return true;
270 }
271 }
272
273 return false;
274 }
275
276 ScriptCommand::Ptr PythonModule::createScriptCommand(const std::string& scriptBasePath, const std::string& relativeScriptPath)
277 {
278 try
279 {
280 auto fullPath = scriptBasePath + relativeScriptPath;
281
282 // Create a new dictionary for the initialisation routine
283 py::dict locals;
284
285 // Disable the flag for initialisation, just to be sure
286 locals["__executeCommand__"] = false;
287
288 // Attempt to run the specified script
289 py::eval_file(fullPath, getGlobals(), locals);
290
291 std::string cmdName;
292 std::string cmdDisplayName;
293
294 if (locals.contains("__commandName__"))
295 {
296 cmdName = locals["__commandName__"].cast<std::string>();
297 }
298
299 if (locals.contains("__commandDisplayName__"))
300 {
301 cmdDisplayName = locals["__commandDisplayName__"].cast<std::string>();
302 }
303
304 if (!cmdName.empty())
305 {
306 if (cmdDisplayName.empty())
307 {
308 cmdDisplayName = cmdName;
309 }
310
311 // Successfully retrieved the command
312 return std::make_shared<ScriptCommand>(cmdName, cmdDisplayName, relativeScriptPath);
313 }
314
315 rError() << "Script file " << relativeScriptPath << " does not export a __commandName__ value" << std::endl;
316 return {};
317 }
318 catch (const py::error_already_set& ex)
319 {
320 rError() << "Script file " << relativeScriptPath << " is not a valid command:" << std::endl;
321 rError() << ex.what() << std::endl;
322 return {};
323 }
324 }
325
326 PythonModule* PythonModule::_instance = nullptr;
327
328 }