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 f1c54f0 commit 1fddcce
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 14 deletions.
11 changes: 5 additions & 6 deletions src/PIL/ImageTk.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,18 @@ 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
try:
tk.call(command, photo, id)
tk.call(command, photo, ptr)
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, repr(ptr))


# --------------------------------------------------------------------
Expand Down Expand Up @@ -181,7 +181,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 +255,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
23 changes: 15 additions & 8 deletions src/Tk/tkImaging.c
Original file line number Diff line number Diff line change
Expand Up @@ -57,18 +57,25 @@ static Tk_PhotoPutBlock_t TK_PHOTO_PUT_BLOCK;
static Imaging
ImagingFind(const char *name) {
Py_ssize_t id;

Check warning on line 59 in src/Tk/tkImaging.c

View workflow job for this annotation

GitHub Actions / ubuntu-latest Python 3.12

unused variable ‘id’ [-Wunused-variable]
PyObject *capsule;
size_t name_len = strlen(name);
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)) ||
strncmp(name + name_len - 1, ">", 1)) {
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 1fddcce

Please sign in to comment.