From ee03ddf0f1d21c58cc42ed18c4dfe2b0f1142209 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:27:51 +0100 Subject: [PATCH] fix(python): each cab screen runs in globals of its own All the Python screens ran in the one __main__ namespace, so a screen could rebind a name another screen, or abstractscreenrenderer itself, relied on. scripts/screen_tablet_km.py (EN57AKM) does `from time import time`, after which file_on_disk() of abstractscreenrenderer failed on Linux, where it looks a file name up in another case, with "AttributeError: 'builtin_function_or_method' object has no attribute 'monotonic'". The same goes on any system for a screen that reads `time` as a module once a tablet screen is loaded, and quietly for the colours, the helpers (trainNumber, headZeros) and the table settings that screens of a vehicle define differently. A screen file now runs in globals of its own, a copy of those of abstractscreenrenderer, so the 51 screens that check `"abstractscreenrenderer" in globals()` still find its class. Its builtins are python's own and the names the screens loaded so far define (the last one's when several do), so a screen that reads a name another screen defines (monitoring4, journeyTimeSecs, czarny) finds it as before. The class of the screen is looked up in its own globals, and in those names when the file doesn't define it. abstractscreenrenderer keeps running in __main__, which the screens no longer change. No change to the game data is needed. --- scripting/PyInt.cpp | 119 +++++++++++++++++++++++++++++++++++++++++--- scripting/PyInt.h | 10 ++++ 2 files changed, 121 insertions(+), 8 deletions(-) diff --git a/scripting/PyInt.cpp b/scripting/PyInt.cpp index b95b310d8..2b751225d 100644 --- a/scripting/PyInt.cpp +++ b/scripting/PyInt.cpp @@ -20,6 +20,60 @@ http://mozilla.org/MPL/2.0/. #endif #include +namespace +{ + +// the file a script is in, looked for in the path given and then in python/local, and its text. no file name when there's none +auto read_script(std::string_view File, std::string_view Path) -> std::pair +{ + std::string const file{File}; + auto const [filepath, fileextension]{FileExists({std::string{Path} + file, "python/local/" + file}, {".py"})}; + if (filepath.empty()) + { + return {}; + } + auto filename{FileOnDisk(filepath + fileextension)}; + std::ifstream inputfile{filename}; + std::string input; + input.assign(std::istreambuf_iterator(inputfile), std::istreambuf_iterator()); + return {std::move(filename), std::move(input)}; +} + +// the builtins of the screens, before any is loaded: a copy of python's own, the names of the screens to be added to it +auto screen_builtins() -> PyObject * +{ + auto *builtinsmodule{PyImport_ImportModule("builtins")}; + if (builtinsmodule == nullptr) + { + return nullptr; + } + auto *builtins{PyDict_Copy(PyModule_GetDict(builtinsmodule))}; + Py_DECREF(builtinsmodule); + return builtins; +} + +// the names a screen defined go to the builtins of the screens, for those that read them without defining them. those of +// abstractscreenrenderer (and __builtins__, __name__) stay as each screen has them, even where the screen rebound them +void share_screen_names(PyObject *Globals, PyObject *Main, PyObject *Builtins) +{ + PyObject *name{nullptr}; + PyObject *value{nullptr}; + Py_ssize_t position{0}; + while (PyDict_Next(Globals, &position, &name, &value) != 0) + { + if (PyDict_Contains(Main, name) != 0) + { + continue; + } + if (PyDict_SetItem(Builtins, name, value) != 0) + { + PyErr_Clear(); + } + } +} + +} // namespace + void render_task::run() { @@ -351,6 +405,13 @@ auto python_taskqueue::init() -> bool { goto release_and_exit; } + // each screen runs in globals of its own, so that one doesn't change the names another (or abstractscreenrenderer) uses + m_screenbuiltins = screen_builtins(); + if (m_screenbuiltins == nullptr) + { + error(); + goto release_and_exit; + } // release the lock, save the state for future use m_mainthread = PyEval_SaveThread(); @@ -416,6 +477,13 @@ void python_taskqueue::exit() Py_XDECREF(rendererobject); } m_renderers.clear(); + for (auto *screenglobals : m_screenglobals) + { + Py_XDECREF(screenglobals); + } + m_screenglobals.clear(); + Py_XDECREF(m_screenbuiltins); + m_screenbuiltins = nullptr; Py_XDECREF(m_stderr); m_stderr = nullptr; Py_XDECREF(m_main); @@ -472,16 +540,12 @@ auto python_taskqueue::insert(task_request const &Task) -> bool auto python_taskqueue::run_file(std::string const &File, std::string const &Path) -> bool { - auto const [filepath, fileextension]{FileExists({Path + File, "python/local/" + File}, {".py"})}; - if (filepath.empty()) + auto const [filename, input]{read_script(File, Path)}; + if (filename.empty()) { return false; } - std::ifstream inputfile{FileOnDisk(filepath + fileextension)}; - std::string input; - input.assign(std::istreambuf_iterator(inputfile), std::istreambuf_iterator()); - if (PyRun_SimpleString(input.c_str()) != 0) { error(); @@ -491,6 +555,37 @@ auto python_taskqueue::run_file(std::string const &File, std::string const &Path return true; } +// runs the script of a screen in globals of its own, which start as a copy of those of abstractscreenrenderer. returns them +// (a new reference), nullptr on failure +auto python_taskqueue::run_screen_file(std::string_view File, std::string_view Path) -> PyObject * +{ + auto const [filename, input]{read_script(File, Path)}; + if (filename.empty()) + { + return nullptr; + } + // the names of abstractscreenrenderer are copied, not left to the builtins: a screen checks globals() for its class + auto *screenglobals{PyDict_Copy(PyModule_GetDict(m_main))}; + if (screenglobals == nullptr) + { + error(); + return nullptr; + } + auto *result{ + PyDict_SetItemString(screenglobals, "__builtins__", m_screenbuiltins) != 0 ? + nullptr : + PyRun_String(input.c_str(), Py_file_input, screenglobals, screenglobals) }; + if (result == nullptr) + { + Py_DECREF(screenglobals); + error(); + return nullptr; + } + Py_DECREF(result); + share_screen_names(screenglobals, PyModule_GetDict(m_main), m_screenbuiltins); + return screenglobals; +} + // acquires the python gil and sets the main thread as current void python_taskqueue::acquire_lock() { @@ -518,6 +613,7 @@ auto python_taskqueue::fetch_renderer(std::string const &Renderer) -> PyObject * PyObject *renderer{nullptr}; PyObject *rendererarguments{nullptr}; PyObject *renderername{nullptr}; + PyObject *screenglobals{nullptr}; acquire_lock(); { if (m_main == nullptr) @@ -526,11 +622,18 @@ auto python_taskqueue::fetch_renderer(std::string const &Renderer) -> PyObject * goto cache_and_return; } - if (false == run_file(file, path)) + screenglobals = run_screen_file(file, path); + if (screenglobals == nullptr) { goto cache_and_return; } - renderername = PyObject_GetAttrString(m_main, file.c_str()); + m_screenglobals.emplace_back(screenglobals); + renderername = PyDict_GetItemString(screenglobals, file.c_str()); // borrowed + if (renderername == nullptr) + { + // a class of that name defined by a screen loaded before, as __main__ had it + renderername = PyDict_GetItemString(m_screenbuiltins, file.c_str()); // borrowed + } if (renderername == nullptr) { ErrorLog("Python Renderer: class \"" + file + "\" not defined"); diff --git a/scripting/PyInt.h b/scripting/PyInt.h index 3259b418a..ad033ceaa 100644 --- a/scripting/PyInt.h +++ b/scripting/PyInt.h @@ -50,7 +50,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" #include "utilities/utilities.h" #include "model/Texture.h" +#include #include +#include #define PyGetFloat(param) PyFloat_FromDouble(param) #define PyGetBool(param) param ? Py_True : Py_False @@ -143,11 +145,19 @@ class python_taskqueue using uploadtask_sequence = threading::lockable>>; // methods auto fetch_renderer(std::string const &Renderer) -> PyObject *; + // runs the script of a screen in globals of its own, which start as a copy of those of abstractscreenrenderer. returns + // them (a new reference), nullptr on failure + auto run_screen_file(std::string_view File, std::string_view Path) -> PyObject *; void run(GLFWwindow *Context, rendertask_sequence &Tasks, uploadtask_sequence &Upload_Tasks, threading::condition_variable &Condition, std::atomic const &Exit); void error(); // members PyObject *m_main{nullptr}; + // the builtins of the screens: python's own, and the names defined by the screens loaded so far, the last one's when + // several define a name. a screen finds there a name it reads but doesn't define itself, as it did when all the screens + // ran in __main__ and one could rebind the names of another + PyObject *m_screenbuiltins{nullptr}; + std::vector m_screenglobals; // the globals of each screen file, kept as long as its classes are PyObject *m_stderr{nullptr}; PyThreadState *m_mainthread{nullptr}; worker_array m_workers;