Skip to content

Commit

Permalink
Use PyCapsule in _imagingtk
Browse files Browse the repository at this point in the history
  • Loading branch information
homm committed Sep 2, 2024
1 parent c69ad03 commit e616daf
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 15 deletions.
12 changes: 6 additions & 6 deletions src/PIL/ImageTk.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,19 @@ def _get_image_from_kw(kw: dict[str, Any]) -> ImageFile.ImageFile | None:


def _pyimagingtkcall(
command: str, photo: PhotoImage | tkinter.PhotoImage, id: int
command: str, photo: PhotoImage | tkinter.PhotoImage, ptr: object
) -> None:
tk = photo.tk
ptr_str = repr(ptr).strip("<>")
try:
tk.call(command, photo, id)
tk.call(command, photo, ptr_str)
except tkinter.TclError:
# activate Tkinter hook
# may raise an error if it cannot attach to Tkinter
from . import _imagingtk

_imagingtk.tkinit(tk.interpaddr())
tk.call(command, photo, id)
tk.call(command, photo, ptr_str)


# --------------------------------------------------------------------
Expand Down Expand Up @@ -181,7 +182,7 @@ def paste(self, im: Image.Image) -> None:
block = image.new_block(self.__mode, im.size)
image.convert2(block, image) # convert directly between buffers

_pyimagingtkcall("PyImagingPhoto", self.__photo, block.id)
_pyimagingtkcall("PyImagingPhoto", self.__photo, block.ptr)


# --------------------------------------------------------------------
Expand Down Expand Up @@ -255,9 +256,8 @@ def __str__(self) -> str:
def getimage(photo: PhotoImage) -> Image.Image:
"""Copies the contents of a PhotoImage to a PIL image memory."""
im = Image.new("RGBA", (photo.width(), photo.height()))
block = im.im

_pyimagingtkcall("PyImagingPhotoGet", photo, block.id)
_pyimagingtkcall("PyImagingPhotoGet", photo, im.im.ptr)

return im

Expand Down
22 changes: 13 additions & 9 deletions src/Tk/tkImaging.c
Original file line number Diff line number Diff line change
Expand Up @@ -56,19 +56,23 @@ static Tk_PhotoPutBlock_t TK_PHOTO_PUT_BLOCK;

static Imaging
ImagingFind(const char *name) {
Py_ssize_t id;
PyObject *capsule;
const char *expected = "capsule object \"" IMAGING_MAGIC "\" at 0x";

/* FIXME: use CObject instead? */
#if defined(_WIN64)
id = _atoi64(name);
#else
id = atol(name);
#endif
if (!id) {
if (strncmp(name, expected, strlen(expected))) {
return NULL;
}

capsule = (PyObject *)strtoull(name + strlen(expected), NULL, 16);

if (!PyCapsule_IsValid(capsule, IMAGING_MAGIC)) {
PyErr_Format(
PyExc_TypeError, "Expected PyCapsule with '%s' name.", IMAGING_MAGIC
);
return NULL;
}

return (Imaging)id;
return (Imaging)PyCapsule_GetPointer(capsule, IMAGING_MAGIC);
}

static int
Expand Down

0 comments on commit e616daf

Please sign in to comment.