| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // Copyright (C) 2026 Tiago V. L. Amorim (@tiagovla) | ||
| 2 | // | ||
| 3 | // This file is part of oiseau (https://github.com/tiagovla/oiseau) | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: GPL-3.0-or-later | ||
| 6 | |||
| 7 | #include "oiseau/plotting/pyplot.hpp" | ||
| 8 | |||
| 9 | #include <stdexcept> | ||
| 10 | |||
| 11 | ✗ | NB_MODULE(_oiseau_plotting, module) { (void)module; } | |
| 12 | |||
| 13 | namespace plt { | ||
| 14 | |||
| 15 | ✗ | py::module_ scoped_interpreter::initialize() { | |
| 16 | ✗ | if (Py_IsInitialized()) throw std::runtime_error("The Python interpreter is already running"); | |
| 17 | |||
| 18 | // Importing a built-in module initializes nanobind in the embedded interpreter. | ||
| 19 | ✗ | static const int registered = PyImport_AppendInittab("_oiseau_plotting", PyInit__oiseau_plotting); | |
| 20 | ✗ | if (registered == -1) throw std::runtime_error("Could not register the plotting module"); | |
| 21 | |||
| 22 | PyConfig config; | ||
| 23 | ✗ | PyConfig_InitPythonConfig(&config); | |
| 24 | ✗ | config.parse_argv = 0; | |
| 25 | ✗ | const auto status = Py_InitializeFromConfig(&config); | |
| 26 | ✗ | PyConfig_Clear(&config); | |
| 27 | ✗ | if (PyStatus_Exception(status)) { | |
| 28 | ✗ | throw std::runtime_error(status.err_msg ? status.err_msg : "Could not initialize Python"); | |
| 29 | } | ||
| 30 | |||
| 31 | ✗ | auto module = py::steal<py::module_>(PyImport_ImportModule("_oiseau_plotting")); | |
| 32 | ✗ | if (!module.is_valid()) fail_initialization(); | |
| 33 | ✗ | return module; | |
| 34 | ✗ | } | |
| 35 | |||
| 36 | ✗ | void scoped_interpreter::fail_initialization() { | |
| 37 | ✗ | PyErr_Print(); | |
| 38 | ✗ | Py_FinalizeEx(); | |
| 39 | ✗ | throw std::runtime_error("Could not initialize the plotting module"); | |
| 40 | } | ||
| 41 | |||
| 42 | ✗ | scoped_interpreter::~scoped_interpreter() { | |
| 43 | ✗ | if (m_active) Py_FinalizeEx(); | |
| 44 | ✗ | } | |
| 45 | |||
| 46 | } // namespace plt | ||
| 47 |