diff --git a/Doc/library/tkinter.rst b/Doc/library/tkinter.rst index 31c0124d3597a9..ea8e6efc25902d 100644 --- a/Doc/library/tkinter.rst +++ b/Doc/library/tkinter.rst @@ -6847,6 +6847,7 @@ Only one handler may be registered per file descriptor. Example code:: widget.tk.deletefilehandler(file) This feature is not available on Windows. +For portable code, use :ref:`channels ` instead. Since you don't know how many bytes are available for reading, you may not want to use the :class:`~io.BufferedIOBase` or :class:`~io.TextIOBase` @@ -6873,6 +6874,112 @@ use raw reads or ``os.read(file.fileno(), maxbytecount)``. Unregisters a file handler. +.. _tkinter-channels: + +Channels +^^^^^^^^ + +A channel lets the Tk mainloop do the I/O on a file, a pipe or a socket, +and call a handler when data can be read or written. +Unlike file handlers, channels work on all platforms, including Windows. +Example code:: + + import tkinter + widget = tkinter.Tk() + channel = widget.tk.createchannel(sock, 'rw') + + def callback(channel, mask): + data = channel.read() + if data == b'': + channel.close() + elif data is not None: + ... + + channel.createhandler(tkinter.READABLE, callback) + +The channel uses a duplicate of the file descriptor, the handle or the socket, +so closing the channel does not close the original object, and vice versa. +But Tcl may read ahead from the duplicate, +so do all I/O through the channel once it is created. +The duplicate shares the blocking mode with the original, +so the original socket, and on POSIX also the original file or pipe, +is switched to non-blocking mode and stays in it after the channel is closed. +Closing the channel shuts down reading from a socket, +so the original socket can still send but no longer receive data. + + +.. method:: Widget.tk.createchannel(file, mode='r', /) + + Create a channel and return it as a :class:`!tkchannel` object. + *file* is a :class:`socket.socket` object, + an object with a :meth:`~io.IOBase.fileno` method, + or an integer file descriptor. + *mode* is ``'r'``, ``'w'`` or ``'rw'``. + Only stream sockets, such as TCP or UNIX sockets, are supported. + On Windows, pass the socket object, not the result of its + :meth:`~socket.socket.fileno` method. + + The channel is binary and non-blocking. + + .. versionadded:: next + + +.. method:: tkchannel.read(size=-1, /) + + Read up to *size* bytes, or all available bytes if *size* is negative. + Return ``b''`` at end of file and ``None`` if no data is available. + + +.. method:: tkchannel.write(data, /) + + Write the :term:`bytes-like object` *data*. + Data which cannot be written at once is written in the background. + + +.. method:: tkchannel.flush() + + Flush the output buffer. + + +.. method:: tkchannel.eof() + + Return ``True`` if the last read reached the end of file. + + +.. method:: tkchannel.createhandler(mask, func, /) + + Register the handler callback function *func*, + replacing the previous handler, if any. + *mask* is an ORed combination of :data:`READABLE` and :data:`WRITABLE`. + The callback is called as follows:: + + callback(channel, mask) + + +.. method:: tkchannel.deletehandler() + + Unregister the handler. + + +.. method:: tkchannel.close() + + Close the channel. + The original file, pipe or socket stays open. + Channels are also context managers which close the channel on exit. + + +.. attribute:: tkchannel.name + + The name of the channel in Tcl, + which can be passed to Tcl commands and Tk options which take a channel, + such as the *channel* option of :meth:`Canvas.postscript`. + + +.. attribute:: tkchannel.closed + + ``True`` if the channel is closed. + + .. data:: READABLE WRITABLE EXCEPTION diff --git a/Doc/whatsnew/3.16.rst b/Doc/whatsnew/3.16.rst index 101be240d23760..8e547411a6b0e3 100644 --- a/Doc/whatsnew/3.16.rst +++ b/Doc/whatsnew/3.16.rst @@ -989,6 +989,13 @@ tkinter the :class:`~tkinter.Text` widget. (Contributed by Serhiy Storchaka in :gh:`159301`.) +* Added support for Tcl :ref:`channels `. + A channel lets the Tk mainloop do the I/O on a file, a pipe or a socket, + and call a handler when data can be read or written. + Unlike :ref:`file handlers `, + channels also work on Windows. + (Contributed by Serhiy Storchaka in :gh:`162537`.) + turtle ------ diff --git a/Lib/test/test_tcl.py b/Lib/test/test_tcl.py index 46a18f727e40d2..8e642190f8bab4 100644 --- a/Lib/test/test_tcl.py +++ b/Lib/test/test_tcl.py @@ -2,6 +2,7 @@ import subprocess import sys import os +import socket import threading from test import support from test.support import import_helper @@ -876,6 +877,198 @@ def test_new_tcl_obj(self): support.check_disallow_instantiation(self, _tkinter.TkappType) +class ChannelTest(unittest.TestCase): + + def setUp(self): + self.tk = Tcl().tk + + def wait(self, channel, mask): + events = [] + channel.createhandler(mask, lambda chan, m: events.append(m)) + try: + for _ in range(1000): + if events: + break + self.tk.dooneevent() + else: + self.fail('no event') + finally: + channel.deletehandler() + self.assertEqual(events[0] & mask, mask) + + def test_pipe(self): + r, w = os.pipe() + self.addCleanup(os.close, r) + self.addCleanup(os.close, w) + with self.tk.createchannel(r) as channel: + self.assertFalse(channel.closed) + self.assertIsInstance(channel.name, str) + self.assertIsNone(channel.read()) + os.write(w, b'ab\0\xff') + self.wait(channel, tkinter.READABLE) + self.assertEqual(channel.read(2), b'ab') + self.assertEqual(channel.read(), b'\0\xff') + self.assertIsNone(channel.read()) + self.assertFalse(channel.eof()) + self.assertTrue(channel.closed) + # The original file descriptor is still open. + os.write(w, b'x') + self.assertEqual(os.read(r, 1), b'x') + + def test_eof(self): + r, w = os.pipe() + self.addCleanup(os.close, r) + with self.tk.createchannel(r) as channel: + os.write(w, b'x') + os.close(w) + self.wait(channel, tkinter.READABLE) + self.assertEqual(channel.read(), b'x') + self.assertEqual(channel.read(), b'') + self.assertTrue(channel.eof()) + + def test_write(self): + r, w = os.pipe() + self.addCleanup(os.close, r) + self.addCleanup(os.close, w) + with self.tk.createchannel(w, 'w') as channel: + self.wait(channel, tkinter.WRITABLE) + channel.write(b'ab\0\xff') + channel.write(bytearray(b'c')) + channel.flush() + self.assertEqual(os.read(r, 10), b'ab\0\xffc') + + def test_socket(self): + a, b = socket.socketpair() + self.addCleanup(a.close) + self.addCleanup(b.close) + with self.tk.createchannel(a, 'rw') as channel: + channel.write(b'ping') + channel.flush() + self.assertEqual(b.recv(10), b'ping') + b.send(b'pong') + self.wait(channel, tkinter.READABLE) + self.assertEqual(channel.read(), b'pong') + # The original socket is still open. + a.send(b'x') + self.assertEqual(b.recv(1), b'x') + + def test_handler(self): + r, w = os.pipe() + self.addCleanup(os.close, r) + self.addCleanup(os.close, w) + channel = self.tk.createchannel(r) + self.addCleanup(channel.close) + calls = [] + def handler(chan, mask): + calls.append((chan, mask)) + chan.read() + chan.deletehandler() + channel.createhandler(tkinter.READABLE, handler) + os.write(w, b'x') + for _ in range(1000): + if calls: + break + self.tk.dooneevent() + self.assertEqual(calls, [(channel, tkinter.READABLE)]) + # Deleting a deleted handler is a no-op. + channel.deletehandler() + + def test_handler_keeps_channel_alive(self): + r, w = os.pipe() + self.addCleanup(os.close, r) + self.addCleanup(os.close, w) + calls = [] + def handler(chan, mask): + calls.append(chan.read()) + chan.close() + self.tk.createchannel(r).createhandler(tkinter.READABLE, handler) + support.gc_collect() + os.write(w, b'x') + for _ in range(1000): + if calls: + break + self.tk.dooneevent() + self.assertEqual(calls, [b'x']) + + def test_close_from_tcl(self): + r, w = os.pipe() + self.addCleanup(os.close, r) + self.addCleanup(os.close, w) + with self.tk.createchannel(w, 'w') as channel: + self.tk.call('puts', '-nonewline', channel.name, 'ab') + self.tk.call('flush', channel.name) + self.assertEqual(os.read(r, 10), b'ab') + # Closing it in Tcl only unregisters the name. + self.tk.call('close', channel.name) + self.assertRaises(TclError, self.tk.call, 'flush', channel.name) + channel.write(b'cd') + channel.flush() + self.assertEqual(os.read(r, 10), b'cd') + + def test_closed(self): + r, w = os.pipe() + self.addCleanup(os.close, r) + self.addCleanup(os.close, w) + channel = self.tk.createchannel(r) + name = channel.name + channel.close() + channel.close() + self.assertTrue(channel.closed) + self.assertRaises(TclError, self.tk.call, 'chan', 'configure', name) + for meth, *args in [('read',), ('write', b'x'), ('flush',), + ('eof',), ('deletehandler',), + ('createhandler', tkinter.READABLE, print)]: + with self.subTest(meth): + self.assertRaises(ValueError, getattr(channel, meth), *args) + self.assertIn('closed', repr(channel)) + + def test_dealloc_closes(self): + r, w = os.pipe() + self.addCleanup(os.close, r) + self.addCleanup(os.close, w) + name = self.tk.createchannel(r).name + support.gc_collect() + self.assertRaises(TclError, self.tk.call, 'chan', 'configure', name) + + def test_bad_arguments(self): + r, w = os.pipe() + self.addCleanup(os.close, r) + self.addCleanup(os.close, w) + for mode in '', 'x', 'rr', 'a': + with self.subTest(mode=mode): + self.assertRaises(ValueError, self.tk.createchannel, r, mode) + self.assertRaises(TypeError, self.tk.createchannel, 'spam') + self.assertRaises(OSError, self.tk.createchannel, os_helper.make_bad_fd()) + with self.tk.createchannel(r) as channel: + self.assertRaises(TypeError, channel.createhandler, + tkinter.READABLE, 'spam') + for mask in 0, tkinter.EXCEPTION, tkinter.READABLE | 0x100: + with self.subTest(mask=mask): + self.assertRaises(ValueError, channel.createhandler, + mask, print) + self.assertRaises(TypeError, channel.write, 'spam') + + @unittest.skipIf(sys.platform == 'win32', 'requires POSIX') + def test_blocking(self): + # The original file shares the blocking mode with the duplicate. + r, w = os.pipe() + self.addCleanup(os.close, r) + self.addCleanup(os.close, w) + self.assertTrue(os.get_blocking(r)) + with self.tk.createchannel(r): + self.assertFalse(os.get_blocking(r)) + self.assertFalse(os.get_blocking(r)) + + @support.cpython_only + def test_dealloc_with_exception(self): + r, w = os.pipe() + self.addCleanup(os.close, r) + self.addCleanup(os.close, w) + # The channel is deallocated while the exception is set. + with self.assertRaises(ZeroDivisionError): + [self.tk.createchannel(r), 1/0] + + class BigmemTclTest(unittest.TestCase): def setUp(self): diff --git a/Misc/NEWS.d/next/Library/2026-11-24-12-00-00.gh-issue-162537.Ch4nNl.rst b/Misc/NEWS.d/next/Library/2026-11-24-12-00-00.gh-issue-162537.Ch4nNl.rst new file mode 100644 index 00000000000000..44122b22382e46 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-24-12-00-00.gh-issue-162537.Ch4nNl.rst @@ -0,0 +1,4 @@ +Added support for Tcl :ref:`channels ` in :mod:`tkinter`. +A channel lets the Tk mainloop do the I/O on a file, a pipe or a socket, and +call a handler when data can be read or written. Unlike file handlers, +channels also work on Windows. diff --git a/Modules/_tkinter.c b/Modules/_tkinter.c index 5eadf6b235e1d7..bbfc261ab26403 100644 --- a/Modules/_tkinter.c +++ b/Modules/_tkinter.c @@ -26,9 +26,7 @@ Copyright (C) 1994 Steen Lumholt. #endif #include "Python.h" -#ifdef MS_WINDOWS -# include "pycore_fileutils.h" // _Py_stat() -#endif +#include "pycore_fileutils.h" // _Py_stat(), _Py_dup() #include "pycore_long.h" // _PyLong_IsNegative() #include "pycore_pyatomic_ft_wrappers.h" // FT_ATOMIC_LOAD_INT_RELAXED() @@ -601,8 +599,9 @@ module _tkinter class _tkinter.tkapp "TkappObject *" "&Tkapp_Type_spec" class _tkinter.Tcl_Obj "PyTclObject *" "&PyTclObject_Type_spec" class _tkinter.tktimertoken "TkttObject *" "&Tktt_Type_spec" +class _tkinter.tkchannel "TkchObject *" "&Tkch_Type_spec" [clinic start generated code]*/ -/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b1ebf15c162ee229]*/ +/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b3fcd661a3bda284]*/ /**** Tkapp Object ****/ @@ -2948,6 +2947,596 @@ _tkinter_tkapp_deletefilehandler_impl(TkappObject *self, PyObject *file) #endif /* HAVE_CREATEFILEHANDLER */ +/**** Tkch Object (channel) ****/ + +static PyObject *Tkch_Type; +#define TkchObject_Check(op) \ + PyObject_TypeCheck((op), (PyTypeObject *)Tkch_Type) + +typedef struct { + PyObject_HEAD + TkappObject *app; + Tcl_Channel channel; /* NULL after close() */ + PyObject *name; + PyObject *func; /* the handler callback, or NULL */ +} TkchObject; + +#define TkchObject_CAST(op) (assert(TkchObject_Check(op)), (TkchObject *)(op)) + +static int +check_channel(TkchObject *self) +{ + if (self->channel == NULL) { + PyErr_SetString(PyExc_ValueError, "I/O operation on closed channel"); + return -1; + } + return check_tcl_appartment(self->app); +} + +static PyObject * +channel_error(int err) +{ + errno = err; + return PyErr_SetFromErrno(PyExc_OSError); +} + +static void +ChannelHandler(ClientData clientData, int mask) +{ + TkchObject *self = TkchObject_CAST(clientData); + PyObject *func, *res; + + ENTER_PYTHON + func = self->func; + if (func != NULL) { + /* The callback can delete the handler or close the channel. */ + Py_INCREF(self); + Py_INCREF(func); + res = PyObject_CallFunction(func, "Oi", (PyObject *)self, mask); + Py_DECREF(func); + if (res == NULL) { + Py_XSETREF(excInCmd, PyErr_GetRaisedException()); + } + Py_XDECREF(res); + Py_DECREF(self); + } + LEAVE_PYTHON +} + +/* Must be called with the GIL held, in the interpreter's thread. */ +static void +Tkch_DeleteHandler(TkchObject *self) +{ + PyObject *func = self->func; + if (func != NULL) { + Tcl_DeleteChannelHandler(self->channel, ChannelHandler, + (ClientData)self); + self->func = NULL; + Py_DECREF(func); + Py_DECREF(self); /* See createhandler() */ + } +} + +/* Unregister the channel from the interpreter (unless a Tcl script has + already closed it there) and drop our own reference, which closes it. + Return the errno of a failed close, or 0. */ +static int +Tkch_Close(TkchObject *self) +{ + Tcl_Channel channel = self->channel; + Tcl_Interp *interp = self->app->interp; + int err = 0; + + self->channel = NULL; + ENTER_TCL + (void)Tcl_UnregisterChannel(interp, channel); + if (Tcl_UnregisterChannel(NULL, channel) != TCL_OK) { + err = Tcl_GetErrno(); + } + LEAVE_TCL + return err; +} + +/*[clinic input] +_tkinter.tkapp.createchannel + + file: object + mode: str = "r" + / + +Create a Tcl channel for a file, a pipe or a socket. + +The channel uses a duplicate of the file descriptor, the handle or +the socket, so closing the channel does not close file, and vice +versa. +[clinic start generated code]*/ + +static PyObject * +_tkinter_tkapp_createchannel_impl(TkappObject *self, PyObject *file, + const char *mode) +/*[clinic end generated code: output=f8ffd257e4efa44f input=785b4482f4b2aade]*/ +{ + int tmode = 0; + Tcl_Channel channel = NULL; + PyObject *socktype, *dupsock = NULL; + TkchObject *v; + int r; + + CHECK_TCL_APPARTMENT(self); + + for (const char *p = mode; *p; p++) { + if (*p == 'r' && !(tmode & TCL_READABLE)) { + tmode |= TCL_READABLE; + } + else if (*p == 'w' && !(tmode & TCL_WRITABLE)) { + tmode |= TCL_WRITABLE; + } + else { + tmode = 0; + break; + } + } + if (tmode == 0) { + PyErr_Format(PyExc_ValueError, "invalid mode: '%s'", mode); + return NULL; + } + + socktype = PyImport_ImportModuleAttrString("_socket", "socket"); + if (socktype == NULL) { + return NULL; + } + r = PyObject_IsInstance(file, socktype); + Py_DECREF(socktype); + if (r < 0) { + return NULL; + } + if (r) { + /* Keep the duplicate in a socket object until the channel owns it, + so that it is closed on error. */ + PyObject *res; + long long sock; + + dupsock = PyObject_CallMethod(file, "dup", NULL); + if (dupsock == NULL) { + return NULL; + } + res = PyObject_CallMethod(dupsock, "fileno", NULL); + if (res == NULL) { + Py_DECREF(dupsock); + return NULL; + } + sock = PyLong_AsLongLong(res); + Py_DECREF(res); + if (sock == -1 && PyErr_Occurred()) { + Py_DECREF(dupsock); + return NULL; + } + ENTER_TCL + channel = Tcl_MakeTcpClientChannel((ClientData)(intptr_t)sock); + LEAVE_TCL + if (channel == NULL) { + Py_DECREF(dupsock); + PyErr_SetString(Tkinter_TclError, + "cannot create a channel for the socket"); + return NULL; + } + res = PyObject_CallMethod(dupsock, "detach", NULL); + Py_DECREF(dupsock); + if (res == NULL) { + /* Cannot happen: the socket is open. */ + return NULL; + } + Py_DECREF(res); + } + else { + int fd = PyObject_AsFileDescriptor(file); + if (fd < 0) { + return NULL; + } +#ifdef MS_WINDOWS + HANDLE handle, duphandle; + handle = _Py_get_osfhandle(fd); + if (handle == INVALID_HANDLE_VALUE) { + return NULL; + } + if (!DuplicateHandle(GetCurrentProcess(), handle, + GetCurrentProcess(), &duphandle, + 0, FALSE, DUPLICATE_SAME_ACCESS)) { + return PyErr_SetFromWindowsErr(0); + } + ENTER_TCL + channel = Tcl_MakeFileChannel((ClientData)duphandle, tmode); + LEAVE_TCL + if (channel == NULL) { + CloseHandle(duphandle); + } +#else + int dupfd = _Py_dup(fd); + if (dupfd < 0) { + return NULL; + } + ENTER_TCL + channel = Tcl_MakeFileChannel((ClientData)(intptr_t)dupfd, tmode); + LEAVE_TCL + if (channel == NULL) { + close(dupfd); + } +#endif + if (channel == NULL) { + PyErr_SetString(Tkinter_TclError, + "cannot create a channel for the file"); + return NULL; + } + } + + ENTER_TCL + /* One reference for the interpreter, so that Tcl commands can use the + channel by name, and one for the Python object, so that the channel + stays valid if a Tcl script closes it. */ + Tcl_RegisterChannel(self->interp, channel); + Tcl_RegisterChannel(NULL, channel); + r = Tcl_SetChannelOption(NULL, channel, "-translation", "binary"); + if (r == TCL_OK) { + r = Tcl_SetChannelOption(NULL, channel, "-blocking", "0"); + } + LEAVE_TCL + + PyTypeObject *tp = (PyTypeObject *)Tkch_Type; + v = (TkchObject *)tp->tp_alloc(tp, 0); + if (v == NULL) { + ENTER_TCL + (void)Tcl_UnregisterChannel(self->interp, channel); + (void)Tcl_UnregisterChannel(NULL, channel); + LEAVE_TCL + return NULL; + } + v->app = (TkappObject *)Py_NewRef(self); + v->channel = channel; + v->func = NULL; + v->name = PyUnicode_FromString(Tcl_GetChannelName(channel)); + if (v->name == NULL) { + Py_DECREF(v); + return NULL; + } + if (r != TCL_OK) { + Py_DECREF(v); + PyErr_SetString(Tkinter_TclError, "cannot configure the channel"); + return NULL; + } + return (PyObject *)v; +} + +/*[clinic input] +_tkinter.tkchannel.read + + size: Py_ssize_t = -1 + / + +Read up to size bytes. + +With a negative size, read all available bytes. Return b'' at end +of file and None if no data is available. +[clinic start generated code]*/ + +static PyObject * +_tkinter_tkchannel_read_impl(TkchObject *self, Py_ssize_t size) +/*[clinic end generated code: output=9c72ae541ae58ba1 input=37265648be02b246]*/ +{ + PyBytesWriter *writer; + Py_ssize_t total = 0; + Tcl_Size chunk, n; + int blocked = 0, err = 0; + + if (check_channel(self) < 0) { + return NULL; + } + chunk = size < 0 ? 8192 : (Tcl_Size)Py_MIN(size, TCL_SIZE_MAX); + writer = PyBytesWriter_Create(chunk); + if (writer == NULL) { + return NULL; + } + for (;;) { + char *buf = (char *)PyBytesWriter_GetData(writer) + total; + ENTER_TCL + n = Tcl_Read(self->channel, buf, chunk); + if (n < 0) { + blocked = Tcl_InputBlocked(self->channel); + err = Tcl_GetErrno(); + } + else if (n == 0) { + blocked = Tcl_InputBlocked(self->channel); + } + LEAVE_TCL + if (n < 0 && !blocked) { + PyBytesWriter_Discard(writer); + return channel_error(err); + } + if (n > 0) { + total += n; + } + if (size >= 0 || n < chunk) { + break; + } + if (PyBytesWriter_Resize(writer, total + chunk) < 0) { + PyBytesWriter_Discard(writer); + return NULL; + } + } + if (total == 0 && blocked) { + PyBytesWriter_Discard(writer); + Py_RETURN_NONE; + } + return PyBytesWriter_FinishWithSize(writer, total); +} + +/*[clinic input] +_tkinter.tkchannel.write + + data: Py_buffer + / + +Write data to the channel. + +The channel is non-blocking: data which cannot be written at once is +written in the background. +[clinic start generated code]*/ + +static PyObject * +_tkinter_tkchannel_write_impl(TkchObject *self, Py_buffer *data) +/*[clinic end generated code: output=05507c2564ff1a04 input=d9ea686cd61b205d]*/ +{ + Tcl_Size n; + int err = 0; + + if (check_channel(self) < 0) { + return NULL; + } + if (data->len > TCL_SIZE_MAX) { + PyErr_SetString(PyExc_OverflowError, "data is too large"); + return NULL; + } + ENTER_TCL + n = Tcl_Write(self->channel, (const char *)data->buf, + (Tcl_Size)data->len); + if (n < 0) { + err = Tcl_GetErrno(); + } + LEAVE_TCL + if (n < 0) { + return channel_error(err); + } + Py_RETURN_NONE; +} + +/*[clinic input] +_tkinter.tkchannel.flush + +Flush the output buffer. +[clinic start generated code]*/ + +static PyObject * +_tkinter_tkchannel_flush_impl(TkchObject *self) +/*[clinic end generated code: output=4ef476dc7d8d7f32 input=4e10a23c59b2b40c]*/ +{ + int r, err = 0; + + if (check_channel(self) < 0) { + return NULL; + } + ENTER_TCL + r = Tcl_Flush(self->channel); + if (r != TCL_OK) { + err = Tcl_GetErrno(); + } + LEAVE_TCL + if (r != TCL_OK) { + return channel_error(err); + } + Py_RETURN_NONE; +} + +/*[clinic input] +_tkinter.tkchannel.eof + +Return True if the end of file was reached by the last read. +[clinic start generated code]*/ + +static PyObject * +_tkinter_tkchannel_eof_impl(TkchObject *self) +/*[clinic end generated code: output=afb48cb23f1ea841 input=ca58827bcfe19239]*/ +{ + if (check_channel(self) < 0) { + return NULL; + } + return PyBool_FromLong(Tcl_Eof(self->channel)); +} + +/*[clinic input] +_tkinter.tkchannel.createhandler + + mask: int + func: object + / + +Set a handler called as func(channel, mask). + +It is called when the channel becomes readable or writable, as +specified by mask. Replace the previous handler, if any. +[clinic start generated code]*/ + +static PyObject * +_tkinter_tkchannel_createhandler_impl(TkchObject *self, int mask, + PyObject *func) +/*[clinic end generated code: output=22a099f226080691 input=176e86e542abec23]*/ +{ + if (check_channel(self) < 0) { + return NULL; + } + if (mask == 0 || (mask & ~(TCL_READABLE | TCL_WRITABLE))) { + PyErr_SetString(PyExc_ValueError, + "mask must be a combination of READABLE and WRITABLE"); + return NULL; + } + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, "func must be callable"); + return NULL; + } + TRACE(self->app, ("((ssOiO))", "#", "createhandler", self->name, + mask, func)); + Tkch_DeleteHandler(self); + /* Extra reference, deleted with the handler: the Tcl event loop + owns the object while the handler is registered. */ + Py_INCREF(self); + self->func = Py_NewRef(func); + Tcl_CreateChannelHandler(self->channel, mask, ChannelHandler, + (ClientData)self); + Py_RETURN_NONE; +} + +/*[clinic input] +_tkinter.tkchannel.deletehandler + +Delete the handler. +[clinic start generated code]*/ + +static PyObject * +_tkinter_tkchannel_deletehandler_impl(TkchObject *self) +/*[clinic end generated code: output=a68f273a10e5eaa9 input=bf864f1f389cf59e]*/ +{ + if (check_channel(self) < 0) { + return NULL; + } + TRACE(self->app, ("((ssO))", "#", "deletehandler", self->name)); + Tkch_DeleteHandler(self); + Py_RETURN_NONE; +} + +/*[clinic input] +_tkinter.tkchannel.close + +Close the channel. + +The file, the pipe or the socket from which the channel was created +stays open. +[clinic start generated code]*/ + +static PyObject * +_tkinter_tkchannel_close_impl(TkchObject *self) +/*[clinic end generated code: output=91067e8aadb114d2 input=5bb6577964a28ad4]*/ +{ + int err; + + if (self->channel == NULL) { + Py_RETURN_NONE; + } + CHECK_TCL_APPARTMENT(self->app); + Tkch_DeleteHandler(self); + err = Tkch_Close(self); + if (err) { + return channel_error(err); + } + Py_RETURN_NONE; +} + +/*[clinic input] +_tkinter.tkchannel.__enter__ + +[clinic start generated code]*/ + +static PyObject * +_tkinter_tkchannel___enter___impl(TkchObject *self) +/*[clinic end generated code: output=aee3228087c0983b input=044c80da55f94457]*/ +{ + if (check_channel(self) < 0) { + return NULL; + } + return Py_NewRef(self); +} + +/*[clinic input] +_tkinter.tkchannel.__exit__ + + exc_type: object + exc_value: object + traceback: object + / + +[clinic start generated code]*/ + +static PyObject * +_tkinter_tkchannel___exit___impl(TkchObject *self, PyObject *exc_type, + PyObject *exc_value, PyObject *traceback) +/*[clinic end generated code: output=68ec14704240ad21 input=07736895fe718905]*/ +{ + return _tkinter_tkchannel_close_impl(self); +} + +static PyObject * +Tkch_get_closed(PyObject *op, void *Py_UNUSED(closure)) +{ + return PyBool_FromLong(TkchObject_CAST(op)->channel == NULL); +} + +static PyObject * +Tkch_get_name(PyObject *op, void *Py_UNUSED(closure)) +{ + return Py_NewRef(TkchObject_CAST(op)->name); +} + +/* Plain casts in the GC slots, as for Tktt (see there). */ + +static int +Tkch_Clear(PyObject *op) +{ + TkchObject *self = (TkchObject *)op; + Py_CLEAR(self->func); + return 0; +} + +static int +Tkch_Traverse(PyObject *op, visitproc visit, void *arg) +{ + TkchObject *self = (TkchObject *)op; + Py_VISIT(Py_TYPE(op)); + Py_VISIT(self->app); + /* Not the extra reference of a registered handler: it is owned by the + Tcl event loop, so the channel is a GC root, not part of a cycle. */ + Py_VISIT(self->func); + return 0; +} + +static void +Tkch_Dealloc(PyObject *op) +{ + TkchObject *self = (TkchObject *)op; + PyTypeObject *tp = Py_TYPE(op); + PyObject_GC_UnTrack(op); + /* No handler can be registered here: it owns a reference. + Tcl can only be called from the interpreter's thread; in another + thread the channel is left open in the interpreter. */ + if (self->channel != NULL && self->app != NULL + && self->app->thread_id == Tcl_GetCurrentThread()) + { + (void)Tkch_Close(self); + } + (void)Tkch_Clear(op); + Py_CLEAR(self->app); + Py_CLEAR(self->name); + tp->tp_free(op); + Py_DECREF(tp); +} + +static PyObject * +Tkch_Repr(PyObject *op) +{ + TkchObject *self = TkchObject_CAST(op); + if (self->channel == NULL) { + return PyUnicode_FromFormat("", self->name); + } + return PyUnicode_FromFormat("", self->name); +} + + /**** Tktt Object (timer token) ****/ static PyObject *Tktt_Type; @@ -3626,6 +4215,48 @@ static PyType_Spec Tktt_Type_spec = { .slots = Tktt_Type_slots, }; +static PyMethodDef Tkch_methods[] = +{ + _TKINTER_TKCHANNEL_READ_METHODDEF + _TKINTER_TKCHANNEL_WRITE_METHODDEF + _TKINTER_TKCHANNEL_FLUSH_METHODDEF + _TKINTER_TKCHANNEL_EOF_METHODDEF + _TKINTER_TKCHANNEL_CREATEHANDLER_METHODDEF + _TKINTER_TKCHANNEL_DELETEHANDLER_METHODDEF + _TKINTER_TKCHANNEL_CLOSE_METHODDEF + _TKINTER_TKCHANNEL___ENTER___METHODDEF + _TKINTER_TKCHANNEL___EXIT___METHODDEF + {NULL, NULL} +}; + +static PyGetSetDef Tkch_getset[] = { + {"name", Tkch_get_name, NULL, "the name of the Tcl channel"}, + {"closed", Tkch_get_closed, NULL, "True if the channel is closed"}, + {NULL} +}; + +static PyType_Slot Tkch_Type_slots[] = { + {Py_tp_dealloc, Tkch_Dealloc}, + {Py_tp_traverse, Tkch_Traverse}, + {Py_tp_clear, Tkch_Clear}, + {Py_tp_repr, Tkch_Repr}, + {Py_tp_methods, Tkch_methods}, + {Py_tp_getset, Tkch_getset}, + {0, 0} +}; + +static PyType_Spec Tkch_Type_spec = { + .name = "_tkinter.tkchannel", + .basicsize = sizeof(TkchObject), + .flags = ( + Py_TPFLAGS_DEFAULT + | Py_TPFLAGS_DISALLOW_INSTANTIATION + | Py_TPFLAGS_IMMUTABLETYPE + | Py_TPFLAGS_HAVE_GC + ), + .slots = Tkch_Type_slots, +}; + /**** Tkapp Method List ****/ @@ -3658,6 +4289,7 @@ static PyMethodDef Tkapp_methods[] = _TKINTER_TKAPP_DELETECOMMAND_METHODDEF _TKINTER_TKAPP_CREATEFILEHANDLER_METHODDEF _TKINTER_TKAPP_DELETEFILEHANDLER_METHODDEF + _TKINTER_TKAPP_CREATECHANNEL_METHODDEF _TKINTER_TKAPP_CREATETIMERHANDLER_METHODDEF _TKINTER_TKAPP_MAINLOOP_METHODDEF _TKINTER_TKAPP_DOONEEVENT_METHODDEF @@ -3844,6 +4476,7 @@ module_clear(PyObject *Py_UNUSED(mod)) Py_CLEAR(Tkinter_TclError); Py_CLEAR(Tkapp_Type); Py_CLEAR(Tktt_Type); + Py_CLEAR(Tkch_Type); Py_CLEAR(PyTclObject_Type); return 0; } @@ -3854,6 +4487,7 @@ module_traverse(PyObject *Py_UNUSED(module), visitproc visit, void *arg) Py_VISIT(Tkinter_TclError); Py_VISIT(Tkapp_Type); Py_VISIT(Tktt_Type); + Py_VISIT(Tkch_Type); Py_VISIT(PyTclObject_Type); return 0; } @@ -3962,6 +4596,12 @@ PyInit__tkinter(void) return NULL; } + Tkch_Type = PyType_FromSpec(&Tkch_Type_spec); + if (PyModule_AddObjectRef(m, "TkchannelType", Tkch_Type)) { + Py_DECREF(m); + return NULL; + } + PyTclObject_Type = PyType_FromSpec(&PyTclObject_Type_spec); if (PyModule_AddObjectRef(m, "Tcl_Obj", PyTclObject_Type)) { Py_DECREF(m); diff --git a/Modules/clinic/_tkinter.c.h b/Modules/clinic/_tkinter.c.h index 6994ebdebaf480..a75b7a7bd977bf 100644 --- a/Modules/clinic/_tkinter.c.h +++ b/Modules/clinic/_tkinter.c.h @@ -2,6 +2,7 @@ preserve [clinic start generated code]*/ +#include "pycore_abstract.h" // _PyNumber_Index() #include "pycore_modsupport.h" // _PyArg_BadArgument() #include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8NoNUL() @@ -499,6 +500,294 @@ _tkinter_tkapp_deletefilehandler(PyObject *self, PyObject *file) #endif /* defined(HAVE_CREATEFILEHANDLER) */ +PyDoc_STRVAR(_tkinter_tkapp_createchannel__doc__, +"createchannel($self, file, mode=\'r\', /)\n" +"--\n" +"\n" +"Create a Tcl channel for a file, a pipe or a socket.\n" +"\n" +"The channel uses a duplicate of the file descriptor, the handle or\n" +"the socket, so closing the channel does not close file, and vice\n" +"versa."); + +#define _TKINTER_TKAPP_CREATECHANNEL_METHODDEF \ + {"createchannel", _PyCFunction_CAST(_tkinter_tkapp_createchannel), METH_FASTCALL, _tkinter_tkapp_createchannel__doc__}, + +static PyObject * +_tkinter_tkapp_createchannel_impl(TkappObject *self, PyObject *file, + const char *mode); + +static PyObject * +_tkinter_tkapp_createchannel(PyObject *self, PyObject *const *args, Py_ssize_t nargs) +{ + PyObject *return_value = NULL; + PyObject *file; + const char *mode = "r"; + + if (!_PyArg_CheckPositional("createchannel", nargs, 1, 2)) { + goto exit; + } + file = args[0]; + if (nargs < 2) { + goto skip_optional; + } + if (!PyUnicode_Check(args[1])) { + _PyArg_BadArgument("createchannel", "argument 2", "str", args[1]); + goto exit; + } + mode = _PyUnicode_AsUTF8NoNUL(args[1]); + if (mode == NULL) { + goto exit; + } +skip_optional: + return_value = _tkinter_tkapp_createchannel_impl((TkappObject *)self, file, mode); + +exit: + return return_value; +} + +PyDoc_STRVAR(_tkinter_tkchannel_read__doc__, +"read($self, size=-1, /)\n" +"--\n" +"\n" +"Read up to size bytes.\n" +"\n" +"With a negative size, read all available bytes. Return b\'\' at end\n" +"of file and None if no data is available."); + +#define _TKINTER_TKCHANNEL_READ_METHODDEF \ + {"read", _PyCFunction_CAST(_tkinter_tkchannel_read), METH_FASTCALL, _tkinter_tkchannel_read__doc__}, + +static PyObject * +_tkinter_tkchannel_read_impl(TkchObject *self, Py_ssize_t size); + +static PyObject * +_tkinter_tkchannel_read(PyObject *self, PyObject *const *args, Py_ssize_t nargs) +{ + PyObject *return_value = NULL; + Py_ssize_t size = -1; + + if (!_PyArg_CheckPositional("read", nargs, 0, 1)) { + goto exit; + } + if (nargs < 1) { + goto skip_optional; + } + { + Py_ssize_t ival = -1; + PyObject *iobj = _PyNumber_Index(args[0]); + if (iobj != NULL) { + ival = PyLong_AsSsize_t(iobj); + Py_DECREF(iobj); + } + if (ival == -1 && PyErr_Occurred()) { + goto exit; + } + size = ival; + } +skip_optional: + return_value = _tkinter_tkchannel_read_impl((TkchObject *)self, size); + +exit: + return return_value; +} + +PyDoc_STRVAR(_tkinter_tkchannel_write__doc__, +"write($self, data, /)\n" +"--\n" +"\n" +"Write data to the channel.\n" +"\n" +"The channel is non-blocking: data which cannot be written at once is\n" +"written in the background."); + +#define _TKINTER_TKCHANNEL_WRITE_METHODDEF \ + {"write", (PyCFunction)_tkinter_tkchannel_write, METH_O, _tkinter_tkchannel_write__doc__}, + +static PyObject * +_tkinter_tkchannel_write_impl(TkchObject *self, Py_buffer *data); + +static PyObject * +_tkinter_tkchannel_write(PyObject *self, PyObject *arg) +{ + PyObject *return_value = NULL; + Py_buffer data = {NULL, NULL}; + + if (PyObject_GetBuffer(arg, &data, PyBUF_SIMPLE) != 0) { + goto exit; + } + return_value = _tkinter_tkchannel_write_impl((TkchObject *)self, &data); + +exit: + /* Cleanup for data */ + if (data.obj) { + PyBuffer_Release(&data); + } + + return return_value; +} + +PyDoc_STRVAR(_tkinter_tkchannel_flush__doc__, +"flush($self, /)\n" +"--\n" +"\n" +"Flush the output buffer."); + +#define _TKINTER_TKCHANNEL_FLUSH_METHODDEF \ + {"flush", (PyCFunction)_tkinter_tkchannel_flush, METH_NOARGS, _tkinter_tkchannel_flush__doc__}, + +static PyObject * +_tkinter_tkchannel_flush_impl(TkchObject *self); + +static PyObject * +_tkinter_tkchannel_flush(PyObject *self, PyObject *Py_UNUSED(ignored)) +{ + return _tkinter_tkchannel_flush_impl((TkchObject *)self); +} + +PyDoc_STRVAR(_tkinter_tkchannel_eof__doc__, +"eof($self, /)\n" +"--\n" +"\n" +"Return True if the end of file was reached by the last read."); + +#define _TKINTER_TKCHANNEL_EOF_METHODDEF \ + {"eof", (PyCFunction)_tkinter_tkchannel_eof, METH_NOARGS, _tkinter_tkchannel_eof__doc__}, + +static PyObject * +_tkinter_tkchannel_eof_impl(TkchObject *self); + +static PyObject * +_tkinter_tkchannel_eof(PyObject *self, PyObject *Py_UNUSED(ignored)) +{ + return _tkinter_tkchannel_eof_impl((TkchObject *)self); +} + +PyDoc_STRVAR(_tkinter_tkchannel_createhandler__doc__, +"createhandler($self, mask, func, /)\n" +"--\n" +"\n" +"Set a handler called as func(channel, mask).\n" +"\n" +"It is called when the channel becomes readable or writable, as\n" +"specified by mask. Replace the previous handler, if any."); + +#define _TKINTER_TKCHANNEL_CREATEHANDLER_METHODDEF \ + {"createhandler", _PyCFunction_CAST(_tkinter_tkchannel_createhandler), METH_FASTCALL, _tkinter_tkchannel_createhandler__doc__}, + +static PyObject * +_tkinter_tkchannel_createhandler_impl(TkchObject *self, int mask, + PyObject *func); + +static PyObject * +_tkinter_tkchannel_createhandler(PyObject *self, PyObject *const *args, Py_ssize_t nargs) +{ + PyObject *return_value = NULL; + int mask; + PyObject *func; + + if (!_PyArg_CheckPositional("createhandler", nargs, 2, 2)) { + goto exit; + } + mask = PyLong_AsInt(args[0]); + if (mask == -1 && PyErr_Occurred()) { + goto exit; + } + func = args[1]; + return_value = _tkinter_tkchannel_createhandler_impl((TkchObject *)self, mask, func); + +exit: + return return_value; +} + +PyDoc_STRVAR(_tkinter_tkchannel_deletehandler__doc__, +"deletehandler($self, /)\n" +"--\n" +"\n" +"Delete the handler."); + +#define _TKINTER_TKCHANNEL_DELETEHANDLER_METHODDEF \ + {"deletehandler", (PyCFunction)_tkinter_tkchannel_deletehandler, METH_NOARGS, _tkinter_tkchannel_deletehandler__doc__}, + +static PyObject * +_tkinter_tkchannel_deletehandler_impl(TkchObject *self); + +static PyObject * +_tkinter_tkchannel_deletehandler(PyObject *self, PyObject *Py_UNUSED(ignored)) +{ + return _tkinter_tkchannel_deletehandler_impl((TkchObject *)self); +} + +PyDoc_STRVAR(_tkinter_tkchannel_close__doc__, +"close($self, /)\n" +"--\n" +"\n" +"Close the channel.\n" +"\n" +"The file, the pipe or the socket from which the channel was created\n" +"stays open."); + +#define _TKINTER_TKCHANNEL_CLOSE_METHODDEF \ + {"close", (PyCFunction)_tkinter_tkchannel_close, METH_NOARGS, _tkinter_tkchannel_close__doc__}, + +static PyObject * +_tkinter_tkchannel_close_impl(TkchObject *self); + +static PyObject * +_tkinter_tkchannel_close(PyObject *self, PyObject *Py_UNUSED(ignored)) +{ + return _tkinter_tkchannel_close_impl((TkchObject *)self); +} + +PyDoc_STRVAR(_tkinter_tkchannel___enter____doc__, +"__enter__($self, /)\n" +"--\n" +"\n"); + +#define _TKINTER_TKCHANNEL___ENTER___METHODDEF \ + {"__enter__", (PyCFunction)_tkinter_tkchannel___enter__, METH_NOARGS, _tkinter_tkchannel___enter____doc__}, + +static PyObject * +_tkinter_tkchannel___enter___impl(TkchObject *self); + +static PyObject * +_tkinter_tkchannel___enter__(PyObject *self, PyObject *Py_UNUSED(ignored)) +{ + return _tkinter_tkchannel___enter___impl((TkchObject *)self); +} + +PyDoc_STRVAR(_tkinter_tkchannel___exit____doc__, +"__exit__($self, exc_type, exc_value, traceback, /)\n" +"--\n" +"\n"); + +#define _TKINTER_TKCHANNEL___EXIT___METHODDEF \ + {"__exit__", _PyCFunction_CAST(_tkinter_tkchannel___exit__), METH_FASTCALL, _tkinter_tkchannel___exit____doc__}, + +static PyObject * +_tkinter_tkchannel___exit___impl(TkchObject *self, PyObject *exc_type, + PyObject *exc_value, PyObject *traceback); + +static PyObject * +_tkinter_tkchannel___exit__(PyObject *self, PyObject *const *args, Py_ssize_t nargs) +{ + PyObject *return_value = NULL; + PyObject *exc_type; + PyObject *exc_value; + PyObject *traceback; + + if (!_PyArg_CheckPositional("__exit__", nargs, 3, 3)) { + goto exit; + } + exc_type = args[0]; + exc_value = args[1]; + traceback = args[2]; + return_value = _tkinter_tkchannel___exit___impl((TkchObject *)self, exc_type, exc_value, traceback); + +exit: + return return_value; +} + PyDoc_STRVAR(_tkinter_tktimertoken_deletetimerhandler__doc__, "deletetimerhandler($self, /)\n" "--\n" @@ -982,4 +1271,4 @@ _tkinter__finalize_thread(PyObject *module, PyObject *Py_UNUSED(ignored)) #ifndef _TKINTER_TKAPP_DELETEFILEHANDLER_METHODDEF #define _TKINTER_TKAPP_DELETEFILEHANDLER_METHODDEF #endif /* !defined(_TKINTER_TKAPP_DELETEFILEHANDLER_METHODDEF) */ -/*[clinic end generated code: output=af52d6870d8c6065 input=a9049054013a1b77]*/ +/*[clinic end generated code: output=4b4792eb63808ccc input=a9049054013a1b77]*/ diff --git a/Tools/c-analyzer/cpython/globals-to-fix.tsv b/Tools/c-analyzer/cpython/globals-to-fix.tsv index 3695208a09f0d5..2c3e5b46b78b63 100644 --- a/Tools/c-analyzer/cpython/globals-to-fix.tsv +++ b/Tools/c-analyzer/cpython/globals-to-fix.tsv @@ -382,6 +382,7 @@ Modules/_testcapi/monitoring.c - PyCodeLike_Type - ## heap types Modules/_tkinter.c - PyTclObject_Type - Modules/_tkinter.c - Tkapp_Type - +Modules/_tkinter.c - Tkch_Type - Modules/_tkinter.c - Tktt_Type - Modules/xxlimited_35.c - Xxo_Type -