| 1 |
#pragma once |
| 2 |
|
| 3 |
#include "itextstream.h" |
| 4 |
#include <pybind11/pybind11.h> |
| 5 |
|
| 6 |
namespace py = pybind11; |
| 7 |
|
| 8 |
namespace script |
| 9 |
{ |
| 10 |
|
| 11 |
/** |
| 12 |
* greebo: A small helper class for redirecting Python's StdIo output |
| 13 |
* to DarkRadiant's global*() streams. |
| 14 |
* |
| 15 |
* The output is duplicated to a given string. |
| 16 |
*/ |
| 17 |
class PythonConsoleWriter |
| 18 |
{ |
| 19 |
private: |
| 20 |
// whether to write to output or error stream |
| 21 |
bool _isErrorLogger; |
| 22 |
|
| 23 |
// A buffer keeping the messages until read |
| 24 |
std::string& _outputBuffer; |
| 25 |
|
| 26 |
public: |
| 27 |
PythonConsoleWriter(bool isErrorLogger, std::string& outputBuffer) : |
| 28 |
_isErrorLogger(isErrorLogger), |
| 29 |
_outputBuffer(outputBuffer) |
| 30 |
{} |
| 31 |
|
| 32 |
// StdOut redirector |
| 33 |
void write(const std::string& msg) |
| 34 |
{ |
| 35 |
_outputBuffer.append(msg); |
| 36 |
|
| 37 |
// Python doesn't send entire lines, it may send single characters, |
| 38 |
// so don't add std::endl each time |
| 39 |
if (_isErrorLogger) |
| 40 |
{ |
| 41 |
rError() << msg; |
| 42 |
} |
| 43 |
else |
| 44 |
{ |
| 45 |
rMessage() << msg; |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
// Since this class serves as "stdout" it should implement flush() |
| 50 |
void flush() |
| 51 |
{ |
| 52 |
// nothing to do here |
| 53 |
} |
| 54 |
}; |
| 55 |
typedef py::class_<PythonConsoleWriter> PythonConsoleWriterClass; |
| 56 |
|
| 57 |
} // namespace script |