File size: 25,135 Bytes
68ce2fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-    */
/* ex: set filetype=cpp softtabstop=4 shiftwidth=4 tabstop=4 cindent expandtab: */

/*
  Author(s):  Andrew LaMora, Peter Kazanzides
  Created on: 2005-02-28

  (C) Copyright 2005-2026 Johns Hopkins University (JHU), All Rights Reserved.

--- begin cisst license - do not edit ---

This software is provided "as is" under an open source license, with
no warranty.  The complete license can be found in license.txt and
http://www.cisst.org/cisst/license.txt.

--- end cisst license ---
*/

#include <Python.h>

#include <cisstCommon/cmnPortability.h>
#include <cisstCommon/cmnCallbackStreambuf.h>
#include <cisstCommon/cmnAssert.h>
#include <cisstInteractive/ireFramework.h>

#if (CISST_OS == CISST_LINUX)
#include <dlfcn.h>
#endif

// PyTextCtrlHook
//
// This class supports displaying cmnLogger output (e.g., from CMN_LOG)
// in an IRE wxTextCtrl window.  All member functions of this class
// are static so that they can easily be passed as function pointers
// (to Python or to cmnCallbackStreambuf).  The class was created primarily
// for organizational purposes -- a namespace may have been just
// as effective.
//
// The display of cmnLogger output is accomplished as follows:
//
//    1. The C++ code (LaunchIREShellInstance) initializes the ireLogger module,
//       starts the Python interpreter, and launches the IRE.
//
//    2. During initialization (in ireMain.py), the IRE calls the
//       PyTextCtrlHook::SetTextOutput C++ function to store the address of a Python
//       callback function (such as wx.PostEvent) as well as the information needed
//       to call PostEvent (window and event class).
//
//    3. The PyTextCtrlHook::SetTextOutput C++ code instantiates a new
//       cmnCallbackStreambuf, passing it the PyTextCtrlHook::PrintLog callback function.
//       After creating the cmnCallbackStreambuf instance, the C++ code adds it as a new
//       channel to the cmnLogger multiplexer.
//
//    4. When the C++ code logs a message, it is sent to the cmnCallbackStreambuf
//       class.  This class calls the callback function (PyTextCtrlHook::PrintLog)
//       whenever a newline is encountered or the buffer is full.
//
//    5. PyTextCtrlHook::PrintLog creates a new Python event instance, sets the character
//       string as an attribute for that event, and then calls the Pythoon callback function
///      (PostEvent) that was specified when PyTextCtrlHook::SetTextOutput was called.
//       This will cause an event to be queued for the GUI thread, which will handle
//       the event and write the text to the wx.TextCtrl object.
//       Note that if a "built-in" (i.e., C) function is specified for the callback,
//       the C function will be called directly via PyCFunction_Call().  In other words,
//       PrintLog will directly call the wxPython DLL, rather than via the Python interpreter.
//
//    6. The Python code calls PyTextCtrlHook::ClearTextOutput when the TextCtrl
//       window is destroyed.
//
// This method is needed because:
//
//    1. Although wxTextCtrl can be derived from a streambuf (via multiple inheritance),
//       that feature is often disabled during compilation of wxWidgets/wxPython.  Furthermore,
//       it is not threadsafe to call wxTextCtrl from different threads.  It is fine, however,
//       to call PostEvent from any thread.
//
//    2. We wish to avoid a dependency on wxWidgets for the C++ code. Thus, we create the event
//       object by calling the PyObject_CallObject, rather than by using the wxWidgets mechanism for
//       creating a new event.
//


class PyTextCtrlHook {
    static PyObject* PythonFunc;         // the Python callback function (i.e., PostEvent)
    static PyObject* PythonEventClass;   // the event object to pass to PostEvent
    static PyObject* PythonWindow;       // the window that will handle the event
    static PyMethodDef Methods[];
#if (PY_MAJOR_VERSION >= 3)
    static PyModuleDef ModuleDef;
#endif
    static cmnCallbackStreambuf<char> *Streambuf;
    static cmnLogMask Mask;

public:
    // Specify the Python callback function
    static PyObject* SetTextOutput(PyObject* self, PyObject* args);
    // Remove the Python callback function
    static PyObject* ClearTextOutput(PyObject* self, PyObject* args);

    // Get the channel log mask
    static PyObject* GetMask(PyObject* self, PyObject* args);
    // Set the channel log mask
    static PyObject* SetMask(PyObject* self, PyObject* args);

    static void SetupStreambuf(void);

    // The C++ callback function that is passed to cmnCallbackStreambuf
    static void PrintLog(const char * str, int len);

    // Initialize the Python module
    static PyObject *InitModule();

    // Cleanup
    static void Cleanup();
};

PyObject* PyTextCtrlHook::PythonFunc = 0;
PyObject* PyTextCtrlHook::PythonEventClass = 0;
PyObject* PyTextCtrlHook::PythonWindow = 0;
cmnCallbackStreambuf<char> *PyTextCtrlHook::Streambuf = 0;
cmnLogMask PyTextCtrlHook::Mask = CMN_LOG_ALLOW_DEFAULT;

// Specify the Python callback function.
PyObject* PyTextCtrlHook::SetTextOutput(PyObject* CMN_UNUSED(self), PyObject* args)
{
    PyObject* func;
    PyObject* evtclass;    // event class
    PyObject* handler;     // handler for GUI window
    int iMask = (int)Mask;
    if (PyArg_ParseTuple(args,"OOO|i",&func,&evtclass,&handler,&iMask)) {
        if (!PyCallable_Check(func)) {
            PyErr_SetString(PyExc_TypeError, "expected a callable for parameter 1.");
            return NULL;
        }
        if (!PyCallable_Check(evtclass)) {
            PyErr_SetString(PyExc_TypeError, "expected a callable (class) for parameter 2.");
            return NULL;
        }
        Py_XINCREF(func);              // Save reference to callback
        Py_XDECREF(PythonFunc);        // Release any previous callback
        PythonFunc = func;
        Py_XINCREF(evtclass);          // Save reference to event
        Py_XDECREF(PythonEventClass);  // Release any previous event
        PythonEventClass = evtclass;
        Py_XINCREF(handler);           // Save reference to handler
        Py_XDECREF(PythonWindow);      // Release any previous handler
        PythonWindow = handler;
        Mask = static_cast<cmnLogMask>(iMask);
        Py_INCREF(Py_None);
        return Py_None;
    }
    return NULL;
}

// Remove the Python callback function
PyObject* PyTextCtrlHook::ClearTextOutput(PyObject* CMN_UNUSED(self), PyObject* CMN_UNUSED(args))
{
    Cleanup();
    Py_INCREF(Py_None);
    return Py_None;
}

// Get the channel log mask
PyObject* PyTextCtrlHook::GetMask(PyObject* CMN_UNUSED(self), PyObject* CMN_UNUSED(args))
{
    // If the channel is active, get the log mask from the multiplexer,
    // just in case it was changed from within the C++ code (very unlikely).
    if (Streambuf) {
        cmnLogger::GetMultiplexer()->GetChannelMask(Streambuf, Mask);
    }
    return Py_BuildValue("i", (int)Mask);
}

// Set the channel log mask
PyObject* PyTextCtrlHook::SetMask(PyObject* CMN_UNUSED(self), PyObject* args)
{
    int iMask;
    if (!PyArg_ParseTuple(args,"i",&iMask)) {
        PyErr_SetString(PyExc_TypeError, "integer type expected");
        return NULL;
    }
    Mask = static_cast<cmnLogMask>(iMask);
    if (Streambuf) {
        cmnLogger::GetMultiplexer()->SetChannelMask(Streambuf, Mask);
    }
    Py_INCREF(Py_None);
    return Py_None;
}

void PyTextCtrlHook::SetupStreambuf(void)
{
    if (!Streambuf) {
        Streambuf = new cmnCallbackStreambuf<char>(PrintLog);
    }
    cmnLogger::GetMultiplexer()->AddChannel(Streambuf, Mask);
}

// The C++ callback function that is passed to cmnCallbackStreambuf.
// It calls the Python callback function stored in PythonFunc.
// Parameters:
//     str:  a null-terminated string
//     len:  the length of the string
void PyTextCtrlHook::PrintLog(const char * str, int CMN_UNUSED(len))
{
    PyObject* result;

    // If PythonFunc is set, we know that PythonEventClass is also set
    // and that both of them are callable objects.
    if (PythonFunc) {
        // For thread safety (get Python global interpreter lock).
        // This function is defined in Python 2.3 or greater.
        PyGILState_STATE gstate = PyGILState_Ensure();

        // Create an instance of the event class and set the msg attribute
        PyObject *empty = Py_BuildValue("()");
        PyObject *kwargs = Py_BuildValue("{s:s}", "msg", str);
        PyObject* event = PyObject_Call(PythonEventClass, empty, kwargs);
        CMN_ASSERT(event);
        Py_DECREF(empty);
        Py_DECREF(kwargs);

        // Build the args for the Python function
        PyObject* args = Py_BuildValue("OO", PythonWindow, event);
        // Decrement "event" reference count (Py_BuildValue incremented it)
        Py_DECREF(event);
        // Call the callback function
#if (PY_MAJOR_VERSION == 2)
        if (PyCFunction_Check(PythonFunc)) {
            // If it is a (wrapped) C function, call it directly.
            try {
                result = PyCFunction_Call(PythonFunc, args, 0);
                result = PyObject_CallObject(PythonFunc, args);
            }
            catch(...) {
                std::cout << "PyCFunction_Call exception" << std::endl;
            }
        }
        else {
            // Call the Python function (via the interpreter)
            result = PyObject_CallObject(PythonFunc, args);
        }
#else
        // Call the Python function (via the interpreter)
        result = PyObject_CallObject(PythonFunc, args);
#endif
        // Decrement reference count
        Py_DECREF(args);

        // If the result is NULL, we had a problem.  Do not write
        // to CMN_LOG because that could lead to an infinite loop
        // (since the logging functions call this function).
        if (result == NULL) {
            std::cout << "CallObject returned NULL" << std::endl;
        } else {
            Py_DECREF(result);
        }

        // Release Python global interpreter lock
        PyGILState_Release(gstate);
    }
}

// Cleanup:  remove logger channel, delete Streambuf object,
//           remove Python callback
void PyTextCtrlHook::Cleanup()
{
    if (Streambuf) {
        cmnLogger::GetMultiplexer()->RemoveChannel(Streambuf);
        delete Streambuf;
        Streambuf = 0;
    }
    if (PythonFunc) {
        Py_XDECREF(PythonFunc);   // Release any previous callback
        PythonFunc = 0;
    }
}

void ireFramework::SetActiveFlag(bool flag)
{
    IRE_State = (flag ? IRE_ACTIVE : IRE_FINISHED);
}

PyObject* SetActiveFlagWrap(PyObject* CMN_UNUSED(self), PyObject* args)
{
    PyObject* pyflag;
    if (PyArg_ParseTuple(args,"O",&pyflag)) {
        ireFramework::SetActiveFlag(pyflag == Py_True);
    }
    return Py_None;
}

PyMethodDef PyTextCtrlHook::Methods[] = {
    { "SetTextOutput", SetTextOutput, METH_VARARGS,"SetTextOutput(func, evtclass, window, mask=current-mask)\n\n"
          "   Set callback function (func) for logging text.\n"
          "   Function should accept a window id and an event object (new instance of evtclass).\n"
          "   mask is channel log mask (defaults to current setting)."
 },
    { "ClearTextOutput", ClearTextOutput, METH_NOARGS, "Clear callback function for logging text."},
    { "GetMask", GetMask, METH_NOARGS, "Get the channel log mask."},
    { "SetMask", SetMask, METH_VARARGS, "Set the channel log mask."},
    { "SetActiveFlag", SetActiveFlagWrap, METH_VARARGS, "Set flag indicating whether IRE is initialized and active."},
    { NULL, NULL, 0, NULL }
};

#if (PY_MAJOR_VERSION >= 3)
PyModuleDef PyTextCtrlHook::ModuleDef = {
    PyModuleDef_HEAD_INIT,
    "ireLogger",
    "ireLogger documentation",
    -1,
    PyTextCtrlHook::Methods,
    NULL,
    NULL,
    NULL,
    NULL
};
#endif

PyObject *PyTextCtrlHook::InitModule()
{
    PyObject *pModule;
#if (PY_MAJOR_VERSION == 2)
    pModule = Py_InitModule("ireLogger", Methods);
#else
    pModule = PyModule_Create(&ModuleDef);
#endif
    if (pModule == NULL) {
        CMN_LOG_INIT_ERROR << "PyTextCtrlHook::InitModule failed" << std::endl;
    }
    return pModule;
}

// ****************************************************************************
// ireFramework static member data
//
bool ireFramework::NewPythonThread = false;
ireFramework::IRE_STATES ireFramework::IRE_State = ireFramework::IRE_NOT_CONSTRUCTED;

void *ireFramework::IreThreadState = 0;

// pInstance was removed from the class so that ireFramework.h does not
// need to include <Python.h>.  This avoids some compiler warnings on Linux.
//PyObject* ireFramework::pInstance = 0;
static PyObject* pInstance = 0;

// ****************************************************************************
// ireFramework::Instance
//
// Return a reference to this one, only, instantiated singleton object.
//
ireFramework* ireFramework::Instance(void) {
    // create a static variable
    static ireFramework instance;
    return &instance;
}

// ****************************************************************************
// ireFramework::InitShellInstance
//
// Initialize the Python shell
//
void ireFramework::InitShellInstance(void)
{
    if (IRE_State != IRE_NOT_CONSTRUCTED) {
        CMN_LOG_INIT_WARNING << "ireFramework already constructed" << std::endl;
        return;
    }
#if (CISST_OS == CISST_LINUX)
    // Need following to avoid having PyExc_ValueError be an undefined symbol
    // when loading the IRE (wxPython version). The Python library is already loaded,
    // but the symbols are not global -- this is fixed by the dlopen call below with
    // RTLD_NOLOAD (doesn't load the library -- assumes it is already loaded).
    char libname[40];
    sprintf(libname, "libpython%d.%d.so", (int)PY_MAJOR_VERSION, (int)PY_MINOR_VERSION);
    dlopen(libname, RTLD_LAZY | RTLD_NOLOAD | RTLD_GLOBAL);
    const char *msg = dlerror();
    if (msg) {
        std::cerr << "InitShellInstance: dlerror when loading " << libname
                           << ": " << msg << std::endl;
        CMN_LOG_INIT_ERROR << "InitShellInstance: dlerror when loading " << libname
                           << ": " << msg << std::endl;
    }
#endif
    IRE_State = IRE_CONSTRUCTED;
}

// ****************************************************************************
// ireFramework::FinalizeShellInstance
//
// Finalize (cleanup) the Python shell.  Also cleans up the PyTextCtrlHook.
//
void ireFramework::FinalizeShellInstance(void)
{
    PyTextCtrlHook::Cleanup();
    Py_XDECREF(pInstance);
    pInstance = 0;
    Py_Finalize();
    // Change the state to IRE_FINISHED (the IRE is probably already in this
    // state).
    IRE_State = IRE_FINISHED;
}

// ****************************************************************************
// LaunchIREShellInstance
//
// This method imports necessary modules and launches the IRE GUI.  It should
// be called AFTER InitShell.
//
// Modules Loaded:
//  - irepy
//
// Developers should take care to DECREF (decrease the reference counts)
// of any PyObject s that use hard references.
//
void ireFramework::LaunchIREShellInstance(const char * startup, bool newPythonThread, IRE_Shell shell,
                                          bool useStreambuf)
{
    if (IRE_State != IRE_CONSTRUCTED) {
        CMN_LOG_INIT_ERROR << "LaunchIREShellInstance:  IRE state is " << IRE_State << "." << std::endl;
        cmnThrow(std::runtime_error("LaunchIREShellInstance: invalid IRE state."));
    }

    NewPythonThread = newPythonThread;

    if (pInstance)
        Py_DECREF(pInstance);
    pInstance = 0;

#if (PY_MAJOR_VERSION == 2)
    Py_Initialize();
    // Set python_args as argv.
    // Note that currently, startup script run separately for IPython.
    const char * python_args[] = { "", startup };
    PySys_SetArgv(2, const_cast<char **>(python_args));
    // Initialize ireLogger module, which is used for the cmnLogger output window
    PyTextCtrlHook::InitModule();
#else
    // Following setting of python_args appears to be necessary when using Python 3
    // with wxPython. Note that currently, startup script run separately for IPython.
    const char * python_args[] = { "", "IRE", startup };
    PyConfig config;
    PyConfig_InitPythonConfig(&config);
    PyConfig_SetBytesArgv(&config, 3, const_cast<char **>(python_args));
    // Initialize ireLogger module, which is used for the cmnLogger output window
    if (PyImport_AppendInittab("ireLogger", PyTextCtrlHook::InitModule) == -1) {
        CMN_LOG_INIT_WARNING << "LaunchIREShellInstance: failed to import ireLogger" << std::endl;
    }
    PyStatus status;
    status = Py_InitializeFromConfig(&config);
    PyConfig_Clear(&config);
    if (PyStatus_IsError(status)) {
        CMN_LOG_INIT_ERROR << "LaunchIREShellInstance: init error: " << status.err_msg << std::endl;
        cmnThrow(std::runtime_error("LaunchIREShellInstance: init error"));
    }
    else if (PyStatus_IsExit(status)) {
        CMN_LOG_INIT_ERROR << "LaunchIREShellInstance: init exit: " << status.err_msg << std::endl;
        cmnThrow(std::runtime_error("LaunchIREShellInstance: init exit"));
    }
#endif
#if (PY_MAJOR_VERSION < 3) || ((PY_MAJOR_VERION == 3) && (PY_MINOR_VERSION < 7))
    // PyEval_InitThreads was deprecated in Python 3.7 (it is no longer needed)
    PyEval_InitThreads();
#endif
#if (CISST_OS == CISST_LINUX)
#if (PY_MAJOR_VERSION == 2)
    // TODO: check if this is needed for Python3
    // For Linux, change dlopenflags to avoid swig::stop_iterator exceptions
    PyGILState_STATE gstate = PyGILState_Ensure();
    PyThreadState *threadState = PyThreadState_Get();
    threadState->interp->dlopenflags |= RTLD_GLOBAL;
    PyGILState_Release(gstate);
#endif
#endif

    IRE_State = IRE_LAUNCHED;

    // Get global dictionary (pModule and pDict are borrowed references)
    PyObject *pModule = PyImport_AddModule("__main__");
    PyObject *pDict = PyModule_GetDict(pModule);
    if (pDict == NULL) {
        IRE_State = IRE_FINISHED;
        PyErr_Clear();
        cmnThrow(std::runtime_error("LaunchIREShellInstance: could not get global dictionary"));
    }

    char launchString[128];
    if (shell == IRE_IPYTHON) {
        // Could instead add "argv=[%s]" to launchString, where %s is startup string
        PyRun_SimpleString(startup);
        // Following code is for very old versions of IPython (possibly prior to 1.0)
        // PyRun_SimpleString("from IPython.Shell import IPShellEmbed\n");
        // PyRun_SimpleString("ipshell = IPShellEmbed()\n");
        // strcpy(launchString, "ipshell(local_ns = globals())");
        PyRun_SimpleString("from IPython.terminal.embed import InteractiveShellEmbed\n");
        PyRun_SimpleString("ipshell = InteractiveShellEmbed()\n");
        strcpy(launchString, "ipshell('Interactive Research Environment (IRE)', local_ns=globals())");
        IRE_State = IRE_ACTIVE;  // for now, instead of using SetActiveState callback
    }
    else if (shell == IRE_JUPYTER) {
        // Store startup code in __main__ - will be set as exec_lines config
        PyRun_SimpleString("_ire_startup_code = ''");
        PyObject* pMainModule = PyImport_AddModule("__main__");
        PyObject* pMainDict = PyModule_GetDict(pMainModule);
        PyObject* pStartupStr = PyUnicode_FromString(startup);
        PyDict_SetItemString(pMainDict, "_ire_startup_code", pStartupStr);
        Py_DECREF(pStartupStr);

        int result = PyRun_SimpleString(
            "def _start_ire_jupyter():\n"
            "    import sys\n"
            "    try:\n"
            "        import asyncio\n"
            "        asyncio.set_event_loop(asyncio.new_event_loop())\n"
            "        from ipykernel.kernelapp import IPKernelApp\n"
            "        from traitlets.config import Config\n"
            "        import __main__\n"
            "        # Configure kernel to run startup code in user namespace\n"
            "        c = Config()\n"
            "        c.InteractiveShellApp.exec_lines = [__main__._ire_startup_code]\n"
            "        _ire_jupyter_app = IPKernelApp.instance(config=c, outstream_class='ipykernel.iostream.OutStream')\n"
            "        # Disable signal handling - kernel runs in subthread\n"
            "        _ire_jupyter_app.init_signal = lambda: None\n"
            "        _ire_jupyter_app.initialize(['python'])\n"
            "        _ire_jupyter_app.start()\n"
            "    except ImportError:\n"
            "        print('ipykernel not found. Install with:')\n"
            "        print('  apt: sudo apt install python3-ipykernel')\n"
            "        print('  pip: pip install ipykernel')\n"
            "        sys.exit(1)\n"
            "    except Exception as e:\n"
            "        import traceback\n"
            "        traceback.print_exc()\n"
            "        sys.exit(1)\n"
        );
        if (result != 0) {
            CMN_LOG_INIT_ERROR << "LaunchIREShellInstance: Python error while attempting to start Jupyter kernel" << std::endl;
            IRE_State = IRE_FINISHED;
            return;
        }
        // Use the same thread infrastructure as IPython: set launchString and
        // fall through to the NewPythonThread block which creates pInstance
        strcpy(launchString, "_start_ire_jupyter()");
        IRE_State = IRE_ACTIVE;
    }
    else {
        PyRun_SimpleString("from irepy import ireMain");
        strcpy(launchString, "ireMain.launchIrePython()");
        if (useStreambuf)
            PyTextCtrlHook::SetupStreambuf();
    }

    if (NewPythonThread) {
        PyRun_SimpleString("import threading\n");
        char buffer[300];
        if (shell == IRE_JUPYTER) {
            sprintf(buffer, "class IreThread(threading.Thread):\n"
                            "    def __init__(self):\n"
                            "        threading.Thread.__init__(self, daemon=True)\n"
                            "    def run(self):\n"
                            "        %s",
                            launchString);
        } else {
            sprintf(buffer, "class IreThread(threading.Thread):\n"
                            "    def __init__(self):\n"
                            "        threading.Thread.__init__(self)\n"
                            "    def run(self):\n"
                            "        %s",
                            launchString);
        }
        PyRun_SimpleString(buffer);
        PyObject* pClass = PyDict_GetItemString(pDict, "IreThread");

        // Create an instance of the class
        if (PyCallable_Check(pClass))
            pInstance = PyObject_CallObject(pClass, NULL);
        if (pInstance) {
            PyObject_CallMethod(pInstance, "start", NULL);
        }
        else {
            IRE_State = IRE_FINISHED;
            PyErr_Clear();
            cmnThrow(std::runtime_error("LaunchIREShellInstance: Could not create IRE thread."));
        }
    }
    else {
        PyRun_SimpleString(launchString);
    }
}

void ireFramework::JoinIREShellInstance(double timeout)
{
    if (NewPythonThread && pInstance && ((IRE_State == IRE_LAUNCHED) || (IRE_State == IRE_ACTIVE))) {
        // First, check whether the Python thread is still alive.
        PyObject *result;

#if (PY_MAJOR_VERSION < 3) || ((PY_MAJOR_VERSION == 3) && (PY_MINOR_VERSION < 5))
        // Prior to Python 3.5, method is called isAlive; was removed in Python 3.9
        result = PyObject_CallMethod(pInstance, "isAlive", NULL);
#else
        // Starting with Python 3.5, method is called is_alive
        result = PyObject_CallMethod(pInstance, "is_alive", NULL);
#endif
        bool isAlive = (result == Py_True);
        Py_DECREF(result);
        if (isAlive) {
            if (timeout >= 0)
                PyObject_CallMethod(pInstance, "join", "(f)", timeout);
            else
                PyObject_CallMethod(pInstance, "join", NULL);
        }
        else
            IRE_State = IRE_FINISHED;
    }
}

bool ireFramework::IsStarting()
{
    return (!IsActive() && !IsFinished());
}

bool ireFramework::IsActive()
{
    return (IRE_State == IRE_ACTIVE);
}

bool ireFramework::IsFinished()
{
    return (IRE_State == IRE_FINISHED);
}

bool ireFramework::IsInitialized()
{
    return (Py_IsInitialized() != 0);
}

void ireFramework::Reset()
{
    if (IRE_State == IRE_FINISHED)
        IRE_State = IRE_CONSTRUCTED;
}

void ireFramework::UnblockThreads()
{
    if ((IRE_State == IRE_LAUNCHED) || (IRE_State == IRE_ACTIVE)) {
#if (PY_MAJOR_VERSION < 3) || ((PY_MAJOR_VERSION == 3) && (PY_MINOR_VERSION < 4))
        IreThreadState = static_cast<void *>(PyEval_SaveThread());
#else
        // PyGilState_Check introduced in Python 3.4
        if (PyGILState_Check()) {
            IreThreadState = static_cast<void *>(PyEval_SaveThread());
        } else {
            IreThreadState = 0;
        }
#endif
    } else {
        IreThreadState = 0;
    }
}

void ireFramework::BlockThreads()
{
    if (IreThreadState)
        PyEval_RestoreThread(static_cast<PyThreadState *>(IreThreadState));
}

void ireFramework::PrintLog(const char * str, int len)
{
    PyTextCtrlHook::PrintLog(str, len);
}