|
| 1 | +#include "python_interpreter.h" |
| 2 | +#include "notebook.h" |
| 3 | +#include "config.h" |
| 4 | +#include <iostream> |
| 5 | +#include <pygobject.h> |
| 6 | + |
| 7 | +inline pybind11::module pyobject_from_gobj(gpointer ptr){ |
| 8 | + auto obj=G_OBJECT(ptr); |
| 9 | + if(obj) |
| 10 | + return pybind11::module(pygobject_new(obj), false); |
| 11 | + return pybind11::module(Py_None, false); |
| 12 | +} |
| 13 | + |
| 14 | +PythonInterpreter::PythonInterpreter(){ |
| 15 | + auto init_juci_api=[](){ |
| 16 | + pybind11::module(pygobject_init(-1,-1,-1), false); |
| 17 | + pybind11::module api("jucpp", "Python bindings for juCi++"); |
| 18 | + api.def("get_current_text_buffer", [](){ |
| 19 | + auto view=Notebook::get().get_current_view(); |
| 20 | + if(view) |
| 21 | + return pyobject_from_gobj(view->gobj()); |
| 22 | + return pybind11::module(Py_None, false); |
| 23 | + }); |
| 24 | + return api.ptr(); |
| 25 | + }; |
| 26 | + PyImport_AppendInittab("jucipp", init_juci_api); |
| 27 | + Py_Initialize(); |
| 28 | + Config::get().load(); |
| 29 | +} |
| 30 | + |
| 31 | +pybind11::module PythonInterpreter::get_loaded_module(const std::string &module_name){ |
| 32 | + return pybind11::module(PyImport_AddModule(module_name.c_str()), true); |
| 33 | +} |
| 34 | + |
| 35 | +pybind11::module PythonInterpreter::import(const std::string &module_name){ |
| 36 | + return pybind11::module(PyImport_ImportModule(module_name.c_str()), false); |
| 37 | +} |
| 38 | + |
| 39 | +void PythonInterpreter::add_path(const boost::filesystem::path &path){ |
| 40 | + std::wstring sys_path(Py_GetPath()); |
| 41 | + if(!sys_path.empty()) |
| 42 | +#ifdef _WIN32 |
| 43 | + sys_path += ';'; |
| 44 | +#else |
| 45 | + sys_path += ':'; |
| 46 | +#endif |
| 47 | + sys_path += path.generic_wstring(); |
| 48 | + Py_SetPath(sys_path.c_str()); |
| 49 | +} |
| 50 | + |
| 51 | +PythonInterpreter::~PythonInterpreter(){ |
| 52 | + auto err=PythonError(); |
| 53 | + if(Py_IsInitialized()) |
| 54 | + Py_Finalize(); |
| 55 | + if(err) |
| 56 | + std::cerr << std::string(err) << std::endl; |
| 57 | +} |
| 58 | + |
| 59 | +PythonError::PythonError(){ |
| 60 | + pybind11::object error(PyErr_Occurred(), false); |
| 61 | + if(error){ |
| 62 | + PyObject *exception,*value,*traceback; |
| 63 | + PyErr_Fetch(&exception,&value,&traceback); |
| 64 | + PyErr_NormalizeException(&exception,&value,&traceback); |
| 65 | + try{ |
| 66 | + exp=std::string(pybind11::object(exception,false).str()); |
| 67 | + val=std::string(pybind11::object(value,false).str()); |
| 68 | + trace=std::string(pybind11::object(traceback,false).str()); |
| 69 | + } catch (const std::runtime_error &e){ |
| 70 | + exp=e.what(); |
| 71 | + } |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +PythonError::operator std::string(){ |
| 76 | + return exp + "\n" + val + "\n" + trace; |
| 77 | +} |
| 78 | + |
| 79 | +PythonError::operator bool(){ |
| 80 | + return !exp.empty(); |
| 81 | +} |
0 commit comments