Debian Codegraph @

plugins/script/PythonModule.h

raw
1 #pragma once
2
3 #include "iscript.h"
4 #include "iscriptinterface.h"
5 #include <functional>
6 #include <memory>
7 #include <pybind11/pybind11.h>
8
9 #include "PythonConsoleWriter.h"
10 #include "ScriptCommand.h"
11
12 namespace py = pybind11;
13
14 namespace script
15 {
16
17 class PythonModule final
18 {
19 private:
20 std::unique_ptr<py::module::module_def> _moduleDef;
21
22 // Python module and global dictionary
23 py::module _module;
24 std::unique_ptr<py::dict> _globals;
25
26 // List of registered interfaces
27 NamedInterfaces _namedInterfaces;
28
29 PythonModule(const PythonModule& other) = delete;
30 PythonModule& operator=(const PythonModule& other) = delete;
31
32 // We need a static reference to the current object, since
33 // PyImport_AppendInittab doesn't allow us to pass user data
34 static PythonModule* _instance;
35
36 // Console and Error output handling
37 std::string _outputBuffer;
38 std::string _errorBuffer;
39
40 PythonConsoleWriter _outputWriter;
41 PythonConsoleWriter _errorWriter;
42
43 bool _interpreterInitialised;
44
45 public:
46 PythonModule();
47 ~PythonModule();
48
49 // Starts up the interpreter, imports the darkradiant module
50 void initialise();
51
52 ExecutionResultPtr executeString(const std::string& scriptString);
53
54 // Execute the given script file
55 void executeScriptFile(const std::string& scriptBasePath, const std::string& relativeScriptPath, bool setExecuteCommandAttr);
56
57 // Get the global object dictionary of this module
58 py::dict& getGlobals();
59
60 void addInterface(const NamedInterface& iface);
61
62 // Attempts to create a script command from the given .py file
63 // Will return an empty object if the file path is not a valid file
64 ScriptCommand::Ptr createScriptCommand(const std::string& scriptBasePath, const std::string& relativeScriptPath);
65
66 private:
67 // Register the darkradiant module with the inittab pointing to InitModule
68 void registerModule();
69
70 bool interfaceExists(const std::string& name);
71
72 // Endpoint called by the Python interface to acquire the module
73 #if PY_MAJOR_VERSION >= 3
74 static PyObject* InitModule();
75 #else
76 static void InitModule();
77 #endif
78
79 PyObject* initialiseModule();
80 };
81
82 }