-
-
Notifications
You must be signed in to change notification settings - Fork 669
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Allow creating images from raw image sources #2263
Changes from all commits
9732208
ef6185a
7ffe38f
218fadb
cf43936
b0600a6
1d2cea7
a1b0f47
472b1c6
d606b95
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
Images can now be created from the native platform representation of an image, without needing to be transformed to bytes. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,10 @@ | ||
from __future__ import annotations | ||
|
||
import sys | ||
import warnings | ||
from io import BytesIO | ||
from pathlib import Path | ||
from typing import TypeVar | ||
from typing import TYPE_CHECKING, Any | ||
from warnings import warn | ||
|
||
try: | ||
|
@@ -19,32 +20,34 @@ | |
# Make sure deprecation warnings are shown by default | ||
warnings.filterwarnings("default", category=DeprecationWarning) | ||
|
||
ImageT = TypeVar("ImageT") | ||
if TYPE_CHECKING: | ||
if sys.version_info < (3, 10): | ||
from typing_extensions import TypeAlias, TypeVar | ||
else: | ||
from typing import TypeAlias, TypeVar | ||
|
||
# Define a type variable for generics where an Image type is required. | ||
ImageT = TypeVar("ImageT") | ||
|
||
# Define the types that can be used as Image content | ||
PathLike: TypeAlias = str | Path | ||
BytesLike: TypeAlias = bytes | bytearray | memoryview | ||
ImageLike: TypeAlias = Any | ||
ImageContent: TypeAlias = PathLike | BytesLike | ImageLike | ||
|
||
|
||
# Note: remove PIL type annotation when plugin system is implemented for image format | ||
# registration; replace with ImageT? | ||
class Image: | ||
def __init__( | ||
self, | ||
src: str | ||
| Path | ||
| bytes | ||
| bytearray | ||
| memoryview | ||
| Image | ||
| PIL.Image.Image | ||
| None = None, | ||
src: ImageContent | None = None, | ||
*, | ||
path=None, # DEPRECATED | ||
data=None, # DEPRECATED | ||
): | ||
"""Create a new image. | ||
|
||
:param src: The source from which to load the image. Can be a file path | ||
(relative or absolute, as a string or :any:`pathlib.Path`), raw | ||
binary data in any supported image format, or another Toga image. Can also | ||
accept a :any:`PIL.Image.Image` if Pillow is installed. | ||
:param src: The source from which to load the image. Can be any valid | ||
:any:`image content <ImageContent>` type. | ||
:param path: **DEPRECATED** - Use ``src``. | ||
:param data: **DEPRECATED** - Use ``src``. | ||
:raises FileNotFoundError: If a path is provided, but that path does not exist. | ||
|
@@ -99,6 +102,9 @@ def __init__( | |
src.save(buffer, format="png", compress_level=0) | ||
self._impl = self.factory.Image(interface=self, data=buffer.getvalue()) | ||
|
||
elif isinstance(src, self.factory.Image.RAW_TYPE): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @rmartin16 If you're looking for a hard-mode typing challenge: How should the type annotation on The only solution I can think of is to add Any ideas? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think this might be possible....but it, perhaps, starts to verge on the ridiculous.... For instance, here's where I got to before I, more or less, gave up: if TYPE_CHECKING:
BaseImageSrcT: TypeAlias = Union[
Path,
bytes,
bytearray,
memoryview,
"Image",
PIL.Image.Image,
None,
]
if sys.platform == "win32":
from toga_winforms.images import WinImage
ImageSrcT: TypeAlias = Union[BaseImageSrcT, WinImage]
if sys.platform.startswith("linux"):
from toga_gtk.images import GdkPixbuf
ImageSrcT: TypeAlias = Union[BaseImageSrcT, GdkPixbuf.Pixbuf]
if sys.platform == "darwin":
from toga_cocoa.images import NSImage
ImageSrcT: TypeAlias = Union[BaseImageSrcT, NSImage]
class Image:
def __init__(self, src: ImageSrcT): ... I'm not sure if mypy technically considers this strategy above part of their larger type narrowing support, but it helps accommodate the runtime environment. That said, for this to really make mypy happy, it'll require other changes in Toga...notably, replacing the star imports in the platform-specific Toga code to explicitly import these native library classes....and we'll also need typing stubs for, at least, PyGObject. BUT...this has major consequences for building docs. On my Linux machine, it tries to interpret the definition of At any rate, the P.S. - type checkers and IDEs are still likely to resolve the type of There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
That was broadly my initial thought as well - except that it falls down on iOS/Android (which will never be installed in the local environment where sys.platform will find it), and on custom backends, and in the Sphinx builds you mention later.
Woof... good luck with that endeavour... I like yaks as much as the next person, but autogeneration of types from GI bindings is a yak to far for me :-)
Is there any advantage to specifying the type at all in this case? What (if any) benefit exists to an explicit There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
I think it depends on your goals. As far as typing is concerned, an untyped argument will be resolved as However, the absence of a type can mean different things. It could mean this function hasn't been evaluated for typing; this would be useful when gradually typing a code base and using mypy's functionality to ignore untyped functions and methods. Although, as you mention, if someone takes That said, given this is part of the API surface, I think it will be useful to ensure it has a type assigned....so, we can know the type has been assessed. So, thinking a bit out of the box perhaps, you could create a There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Replacing all the specific Image classes with an There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Additionally, fwiw, using There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ugh... fine, I guess we'll just go with There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The docs still look quite cluttered with everything in the union. Can we just make ImageType an alias for Any, and then describe all the options in its docstring? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. See the discussion above - that's where I started, and it looks awful; it renders in Sphinx as I'm open to other suggestions, but putting There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Since a union that contains Any no longer provides any type-checking safety, and there are so many things in the union that it isn't very good documentation either, my suggestion was to just replace the whole union with Any, and rely on the documentation text to explain what's accepted. Ideally we would do this with an alias, but if Sphinx doesn't work with that, we can use Any directly, and put the documentation in its own section on the Image page with incoming links from all the relevant places. |
||
self._impl = self.factory.Image(interface=self, raw=src) | ||
|
||
else: | ||
raise TypeError("Unsupported source type for Image") | ||
|
||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is imported in one place, and added to the spelling wordlist, but It doesn't looks like it's actually being used.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It was pre-existing; it's used in all the
as_image()
(canvas, image view) andas_format()
(Image) calls.It's in the dictionary now because the default sphinx handling of type annotations apparently considers the type to be a word that needs to be spell checked. The previous plugin didn't do this.