#ifndef Py_BUILD_CORE_BUILTIN
# define Py_BUILD_CORE_MODULE 1
#endif
#include "Python.h"
#ifdef MS_WINDOWS
#include "pycore_fileutils.h"
#include "pycore_runtime.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <fcntl.h>
typedef struct {
PyObject_HEAD
int fd;
} winconsoleio;
static int execfunc(PyObject *m)
{
return 0;
}
PyModuleDef_Slot testconsole_slots[] = {
{Py_mod_exec, execfunc},
{Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
{0, NULL},
};
static PyObject *
_testconsole_write_input_impl(PyObject *module, PyObject *file,
PyBytesObject *s)
{
INPUT_RECORD *rec = NULL;
PyTypeObject *winconsoleio_type = (PyTypeObject *)_PyImport_GetModuleAttr(
&_Py_ID(_io), &_Py_ID(_WindowsConsoleIO));
if (winconsoleio_type == NULL) {
return NULL;
}
int is_subclass = PyObject_TypeCheck(file, winconsoleio_type);
Py_DECREF(winconsoleio_type);
if (!is_subclass) {
PyErr_SetString(PyExc_TypeError, "expected raw console object");
return NULL;
}
const wchar_t *p = (const wchar_t *)PyBytes_AS_STRING(s);
DWORD size = (DWORD)PyBytes_GET_SIZE(s) / sizeof(wchar_t);
rec = (INPUT_RECORD*)PyMem_Calloc(size, sizeof(INPUT_RECORD));
if (!rec)
goto error;
INPUT_RECORD *prec = rec;
for (DWORD i = 0; i < size; ++i, ++p, ++prec) {
prec->EventType = KEY_EVENT;
prec->Event.KeyEvent.bKeyDown = TRUE;
prec->Event.KeyEvent.wRepeatCount = 1;
prec->Event.KeyEvent.uChar.UnicodeChar = *p;
}
HANDLE hInput = _Py_get_osfhandle(((winconsoleio*)file)->fd);
if (hInput == INVALID_HANDLE_VALUE)
goto error;
DWORD total = 0;
while (total < size) {
DWORD wrote;
if (!WriteConsoleInputW(hInput, &rec[total], (size - total), &wrote)) {
PyErr_SetFromWindowsErr(0);
goto error;
}
total += wrote;
}
PyMem_Free((void*)rec);
Py_RETURN_NONE;
error:
if (rec)
PyMem_Free((void*)rec);
return NULL;
}
static PyObject *
_testconsole_read_output_impl(PyObject *module, PyObject *file)
{
Py_RETURN_NONE;
}
#include "clinic\_testconsole.c.h"
PyMethodDef testconsole_methods[] = {
_TESTCONSOLE_WRITE_INPUT_METHODDEF
_TESTCONSOLE_READ_OUTPUT_METHODDEF
{NULL, NULL}
};
static PyModuleDef testconsole_def = {
PyModuleDef_HEAD_INIT,
"_testconsole",
PyDoc_STR("Test module for the Windows console"),
0,
testconsole_methods,
testconsole_slots,
NULL,
NULL,
NULL,
};
PyMODINIT_FUNC
PyInit__testconsole(PyObject *spec)
{
return PyModuleDef_Init(&testconsole_def);
}
#endif