forked from root-project/root
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRPyROOTApplication.cxx
More file actions
228 lines (193 loc) · 7.68 KB
/
Copy pathRPyROOTApplication.cxx
File metadata and controls
228 lines (193 loc) · 7.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// Author: Enric Tejedor CERN 04/2019
// Original PyROOT code by Wim Lavrijsen, LBL
/*************************************************************************
* Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
// Bindings
#include <Python.h>
#include "RPyROOTApplication.h"
// ROOT
#include "TInterpreter.h"
#include "TSystem.h"
#include "TBenchmark.h"
#include "TStyle.h"
#include "TError.h"
#include "Getline.h"
#include "TVirtualMutex.h"
#include "TVirtualPad.h"
#include "TROOT.h"
////////////////////////////////////////////////////////////////////////////
/// \brief Create an RPyROOTApplication.
/// \param[in] ignoreCmdLineOpts True if Python command line options should
/// be ignored.
/// \return false if gApplication is not null, true otherwise.
///
/// If ignoreCmdLineOpts is false, this method processes the command line
/// arguments from sys.argv. A distinction between arguments for
/// TApplication and user arguments can be made by using "-" or "--" as a
/// separator on the command line.
///
/// For example, to enable batch mode from the command line:
/// > python script_name.py -b -- user_arg1 ... user_argn
/// or, if the user script receives no arguments:
/// > python script_name.py -b
bool PyROOT::RPyROOTApplication::CreateApplication(int ignoreCmdLineOpts)
{
if (!gApplication) {
int argc = 1;
char **argv = nullptr;
if (ignoreCmdLineOpts) {
// Last argv must be null (see https://en.cppreference.com/cpp/language/main_function)
argv = new char *[argc + 1] {};
} else {
// Retrieve sys.argv list from Python
PyObject *argl = PySys_GetObject("argv");
if (argl) {
Py_ssize_t size = PyList_Size(argl);
if (size > 0)
argc = static_cast<int>(size);
}
// Last argv must be null (see https://en.cppreference.com/cpp/language/main_function)
argv = new char *[argc + 1] {};
for (int i = 1; i < argc; ++i) {
PyObject *item = PyList_GetItem(argl, i);
const char *argi = PyUnicode_AsUTF8AndSize(item, nullptr);
if (strcmp(argi, "-") == 0 || strcmp(argi, "--") == 0) {
// Stop collecting options, the remaining are for the Python script
argc = i; // includes program name
break;
}
argv[i] = const_cast<char *>(argi);
}
}
argv[0] = (char *)"python";
gApplication = new RPyROOTApplication("PyROOT", &argc, argv);
delete[] argv; // TApplication ctor has copied argv, so done with it
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////
/// \brief Setup the basic ROOT globals gBenchmark, gStyle and gProgname,
/// if not already set.
void PyROOT::RPyROOTApplication::InitROOTGlobals()
{
if (!gBenchmark)
gBenchmark = new TBenchmark();
if (!gStyle)
gStyle = new TStyle();
if (!gProgName) // should have been set by TApplication
gSystem->SetProgname("python");
}
////////////////////////////////////////////////////////////////////////////
/// \brief Translate ROOT error/warning to Python.
static void ErrMsgHandler(int level, Bool_t abort, const char *location, const char *msg)
{
// Initialization from gEnv (the default handler will return w/o msg b/c level too low)
if (gErrorIgnoreLevel == kUnset)
::DefaultErrorHandler(kUnset - 1, kFALSE, "", "");
if (level < gErrorIgnoreLevel)
return;
// Turn warnings into Python warnings
if (level >= kError) {
::DefaultErrorHandler(level, abort, location, msg);
} else if (level >= kWarning) {
static const char *emptyString = "";
if (!location)
location = emptyString;
// This warning might be triggered while holding the ROOT lock, while
// some other thread is holding the GIL and waiting for the ROOT lock.
// That will trigger a deadlock.
// So if ROOT is in MT mode, use ROOT's error handler that doesn't take
// the GIL.
if (!gGlobalMutex) {
// Either printout or raise exception, depending on user settings
auto state = PyGILState_Ensure();
PyErr_WarnExplicit(NULL, (char *)msg, (char *)location, 0, (char *)"ROOT", NULL);
PyGILState_Release(state);
} else {
::DefaultErrorHandler(level, abort, location, msg);
}
} else {
::DefaultErrorHandler(level, abort, location, msg);
}
}
////////////////////////////////////////////////////////////////////////////
/// \brief Install the ROOT message handler which will turn ROOT error
/// messages into Python exceptions.
void PyROOT::RPyROOTApplication::InitROOTMessageCallback()
{
SetErrorHandler((ErrorHandlerFunc_t)&ErrMsgHandler);
}
////////////////////////////////////////////////////////////////////////////
/// \brief Initialize an RPyROOTApplication.
/// \param[in] self Always null, since this is a module function.
/// \param[in] args [0] Boolean that tells whether to ignore the command line options.
PyObject *PyROOT::RPyROOTApplication::InitApplication(PyObject * /*self*/, PyObject *args)
{
int argc = PyTuple_Size(args);
if (argc == 1) {
PyObject *ignoreCmdLineOpts = PyTuple_GetItem(args, 0);
if (!PyBool_Check(ignoreCmdLineOpts)) {
PyErr_SetString(PyExc_TypeError, "Expected boolean type as argument.");
return nullptr;
}
if (CreateApplication(PyObject_IsTrue(ignoreCmdLineOpts))) {
InitROOTGlobals();
InitROOTMessageCallback();
}
} else {
PyErr_Format(PyExc_TypeError, "Expected 1 argument, %d passed.", argc);
return nullptr;
}
Py_RETURN_NONE;
}
////////////////////////////////////////////////////////////////////////////
/// \brief Construct a TApplication for PyROOT.
/// \param[in] name Application class name.
/// \param[in] argc Number of arguments.
/// \param[in] argv Arguments.
PyROOT::RPyROOTApplication::RPyROOTApplication(const char *name, int *argc, char **argv)
: TApplication(name, argc, argv)
{
// Save current interpreter context
gInterpreter->SaveContext();
gInterpreter->SaveGlobalsContext();
// Prevent crashes on accessing history
Gl_histinit((char *)"-");
// Prevent ROOT from exiting python
SetReturnFromRun(true);
}
namespace {
static int (*sOldInputHook)() = nullptr;
static PyThreadState *sInputHookEventThreadState = nullptr;
static int EventInputHook()
{
// This method is supposed to be called from CPython's command line and
// drives the GUI
PyEval_RestoreThread(sInputHookEventThreadState);
if (gPad && gPad->IsWeb())
gPad->UpdateAsync();
gSystem->ProcessEvents();
PyEval_SaveThread();
if (sOldInputHook)
return sOldInputHook();
return 0;
}
} // unnamed namespace
////////////////////////////////////////////////////////////////////////////
/// \brief Install a method hook for sending events to the GUI.
/// \param[in] self Always null, since this is a module function.
/// \param[in] args Pointer to an empty Python tuple.
PyObject *PyROOT::RPyROOTApplication::InstallGUIEventInputHook(PyObject * /* self */, PyObject * /* args */)
{
if (PyOS_InputHook && PyOS_InputHook != &EventInputHook)
sOldInputHook = PyOS_InputHook;
sInputHookEventThreadState = PyThreadState_Get();
PyOS_InputHook = (int (*)()) & EventInputHook;
Py_RETURN_NONE;
}