Skip to content
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

Merged
merged 10 commits into from
Dec 13, 2023
8 changes: 6 additions & 2 deletions android/src/toga_android/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,21 @@


class Image:
def __init__(self, interface, path=None, data=None):
RAW_TYPE = Bitmap

def __init__(self, interface, path=None, data=None, raw=None):
self.interface = interface

if path:
self.native = BitmapFactory.decodeFile(str(path))
if self.native is None:
raise ValueError(f"Unable to load image from {path}")
else:
elif data:
self.native = BitmapFactory.decodeByteArray(data, 0, len(data))
if self.native is None:
raise ValueError("Unable to load image from data")
else:
self.native = raw

def get_width(self):
return self.native.getWidth()
Expand Down
1 change: 1 addition & 0 deletions changes/2263.feature.rst
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.
8 changes: 6 additions & 2 deletions cocoa/src/toga_cocoa/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ def nsdata_to_bytes(data: NSData) -> bytes:


class Image:
def __init__(self, interface, path=None, data=None):
RAW_TYPE = NSImage

def __init__(self, interface, path=None, data=None, raw=None):
self.interface = interface

try:
Expand All @@ -36,11 +38,13 @@ def __init__(self, interface, path=None, data=None):
self.native = image.initWithContentsOfFile(str(path))
if self.native is None:
raise ValueError(f"Unable to load image from {path}")
else:
elif data:
nsdata = NSData.dataWithBytes(data, length=len(data))
self.native = image.initWithData(nsdata)
if self.native is None:
raise ValueError("Unable to load image from data")
else:
self.native = raw
finally:
image.release()

Expand Down
2 changes: 2 additions & 0 deletions core/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ dev = [
"pytest-freezer == 0.4.8",
"setuptools-scm == 8.0.4",
"tox == 4.11.4",
# typing-extensions needed for TypeAlias added in Py 3.10
"typing-extensions == 4.9.0 ; python_version < '3.10'"
]
docs = [
"furo == 2023.9.10",
Expand Down
38 changes: 22 additions & 16 deletions core/src/toga/images.py
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:
Expand All @@ -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")
Comment on lines +29 to +30
Copy link
Member

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.

Copy link
Member Author

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) and as_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.


# 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.
Expand Down Expand Up @@ -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):
Copy link
Member Author

Choose a reason for hiding this comment

The 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 src be modified to allow for this? It's a type on a class that, by definition, is platform specific, and won't exist in the environment where toga-core is being built, tested, or documented.

The only solution I can think of is to add UIImage | NSImage | GdkBitmap | ... but that won't be correct - you can't use a UIImage unless you're on iOS.

Any ideas?

Copy link
Member

@rmartin16 rmartin16 Dec 7, 2023

Choose a reason for hiding this comment

The 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 ImageSrcT for Linux but cannot find toga_gtk; I can install toga_gtk to build the docs....but then the build blows up with RuntimeErrors about DISPLAY env var. Maybe Sphinx has some buried support for effectively ignoring certain symbols...and that could serve as some type of resolution here.

At any rate, the src argument feels like a good candidate for Any where the documentation fills in the details.

P.S. - type checkers and IDEs are still likely to resolve the type of src to Any even with all these accommodations if Pillow isn't installed. And if we just add these platform-specific image classes, such as GdkPixbuf.Pixbuf, then the type will always be Any because it would be impossible to resolve all the types in the Union on any one system.

Copy link
Member Author

Choose a reason for hiding this comment

The 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:

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.

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.

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 :-)

At any rate, the src argument feels like a good candidate for Any where the documentation fills in the details.

Is there any advantage to specifying the type at all in this case? What (if any) benefit exists to an explicit Any over "no type declaration"? Cosmetically, "Any" reads to me as "You can use literally anything", which isn't true (at least, not in spirit). This is a case where I think I'd prefer to say nothing, and force the reader to actually read words, rather than provide something explicitly too broad as an automated description.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any advantage to specifying the type at all in this case? What (if any) benefit exists to an explicit Any over "no type declaration"? Cosmetically, "Any" reads to me as "You can use literally anything", which isn't true (at least, not in spirit). This is a case where I think I'd prefer to say nothing, and force the reader to actually read words, rather than provide something explicitly too broad as an automated description.

I think it depends on your goals.

As far as typing is concerned, an untyped argument will be resolved as Any...so, in that regard, adding Any or not in this case is functionally the same.

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 Any seriously, then they will be especially misled on what this argument can accept.

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 NewType called ImageDataT that's just assigned to Any. In that way, it's an indication a specific type is being requested....it just isn't expressed in Python types.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replacing all the specific Image classes with an ImageT that maps to Any seems like a decent option that is going to render well as documentation, and won't be intractable from a mypy perspective. I'll go with that.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Additionally, fwiw, using NewType wouldn't really work either....since it would, in fact, require users to explicitly cast the image data as ImageType which wouldn't be a great experience at all.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ugh... fine, I guess we'll just go with Any in the union then... le sigh...

Copy link
Member

Choose a reason for hiding this comment

The 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?

Copy link
Member Author

Choose a reason for hiding this comment

The 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 NewType("Image", Any), with the sphinx link to "NewType" being to the Python docs. AFAIK, it's not possible to provide documentation for the type itself (which would be the ideal situation).

I'm open to other suggestions, but putting Any in the union is the only version I could find that mollifies mypy/PyCharm and doesn't read like a train wreck.

Copy link
Member

Choose a reason for hiding this comment

The 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")

Expand Down
36 changes: 9 additions & 27 deletions core/src/toga/widgets/imageview.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,7 @@
from toga.widgets.base import Widget

if TYPE_CHECKING:
from pathlib import Path

import PIL.Image

from toga.images import ImageT
from toga.images import ImageContent, ImageT


def rehint_imageview(image, style, scale=1):
Expand All @@ -24,9 +20,9 @@ def rehint_imageview(image, style, scale=1):
:param image: The image being displayed.
:param style: The style object for the imageview.
:param scale: The scale factor (if any) to apply to native pixel sizes.
:returns: A triple containing the intrinsic width hint, intrinsic height
hint, and the aspect ratio to preserve (or None if the aspect ratio
should not be preserved).
:returns: A triple containing the intrinsic width hint, intrinsic height hint, and
the aspect ratio to preserve (or None if the aspect ratio should not be
preserved).
"""
if image:
if style.width != NONE and style.height != NONE:
Expand Down Expand Up @@ -72,23 +68,15 @@ def rehint_imageview(image, style, scale=1):
class ImageView(Widget):
def __init__(
self,
image: str
| Path
| bytes
| bytearray
| memoryview
| PIL.Image.Image
| None = None,
image: ImageContent | None = None,
id=None,
style=None,
):
"""
Create a new image view.

:param image: The image to display. This can take all the same formats as the
`src` parameter to :class:`toga.Image` -- namely, a file path (as string
or :any:`pathlib.Path`), bytes data in a supported image format,
or :any:`PIL.Image.Image`.
:param image: The image to display. Can be any valid :any:`image content
<ImageContent>` type; or :any:`None` to display no image.
:param id: The ID for the widget.
:param style: A style object. If no style is provided, a default style will be
applied to the widget.
Expand Down Expand Up @@ -120,14 +108,8 @@ def focus(self):
def image(self) -> toga.Image | None:
"""The image to display.

When setting an image, you can provide:

* An :class:`~toga.images.Image` instance; or

* Any value that would be a valid path specifier when creating a new
:class:`~toga.images.Image` instance; or

* :any:`None` to clear the image view.
When setting an image, you can provide any valid :any:`image content
<ImageContent>` type; or :any:`None` to clear the image view.
"""
return self._image

Expand Down
6 changes: 5 additions & 1 deletion core/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ def clear_sys_modules(monkeypatch):
pass


class TestApp(toga.App):
pass


@pytest.fixture
def app(event_loop):
return toga.App(formal_name="Test App", app_id="org.beeware.toga.test-app")
return TestApp(formal_name="Test App", app_id="org.beeware.toga.test-app")
41 changes: 32 additions & 9 deletions core/tests/test_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
import toga
from toga_dummy.utils import assert_action_performed_with

RELATIVE_FILE_PATH = Path("resources/toga.png")
ABSOLUTE_FILE_PATH = Path(toga.__file__).parent / "resources/toga.png"
RELATIVE_FILE_PATH = Path("resources/sample.png")
ABSOLUTE_FILE_PATH = Path(__file__).parent / "resources/sample.png"


@pytest.mark.filterwarnings("ignore::DeprecationWarning")
Expand Down Expand Up @@ -108,6 +108,20 @@ def test_create_from_bytes(args, kwargs):
assert_action_performed_with(image, "load image data", data=BYTES)


def test_create_from_raw():
"""An image can be created from a raw data source"""
orig = toga.Image(BYTES)

copy = toga.Image(orig._impl.native)
# Image is bound
assert copy._impl is not None
# impl/interface round trips
assert copy._impl.interface == copy

# Image was constructed from raw data
assert_action_performed_with(copy, "load image from raw")


def test_not_enough_arguments():
with pytest.raises(
TypeError,
Expand All @@ -132,7 +146,7 @@ def test_create_from_pil(app):
toga_image = toga.Image(pil_image)

assert isinstance(toga_image, toga.Image)
assert toga_image.size == (32, 32)
assert toga_image.size == (144, 72)


def test_create_from_toga_image(app):
Expand All @@ -141,7 +155,7 @@ def test_create_from_toga_image(app):
toga_image_2 = toga.Image(toga_image)

assert isinstance(toga_image_2, toga.Image)
assert toga_image_2.size == (32, 32)
assert toga_image_2.size == (144, 72)


@pytest.mark.parametrize("kwargs", [{"data": BYTES}, {"path": ABSOLUTE_FILE_PATH}])
Expand Down Expand Up @@ -176,14 +190,23 @@ def test_dimensions(app):
"""The dimensions of the image can be retrieved"""
image = toga.Image(RELATIVE_FILE_PATH)

assert image.size == (32, 32)
assert image.width == image.height == 32
assert image.size == (144, 72)
assert image.width == 144
assert image.height == 72


def test_data(app):
"""The raw data of the image can be retrieved."""
image = toga.Image(ABSOLUTE_FILE_PATH)
assert image.data == ABSOLUTE_FILE_PATH.read_bytes()

# We can't guarantee the round-trip of image data,
# but the data starts with a PNG header
assert image.data.startswith(b"\x89PNG\r\n\x1a\n")

# If we build a new image from the data, it has the same properties.
from_data = toga.Image(image.data)
assert from_data.width == image.width
assert from_data.height == image.height


def test_image_save(tmp_path):
Expand Down Expand Up @@ -214,15 +237,15 @@ def test_as_format_toga(app, Class_1, Class_2):
image_2 = image_1.as_format(Class_2)

assert isinstance(image_2, Class_2)
assert image_2.size == (32, 32)
assert image_2.size == (144, 72)


def test_as_format_pil(app):
"""as_format can successfully return a PIL image"""
toga_image = toga.Image(ABSOLUTE_FILE_PATH)
pil_image = toga_image.as_format(PIL.Image.Image)
assert isinstance(pil_image, PIL.Image.Image)
assert pil_image.size == (32, 32)
assert pil_image.size == (144, 72)


# None is same as supplying nothing; also test a random unrecognized class
Expand Down
5 changes: 2 additions & 3 deletions core/tests/test_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import pytest

import toga
import toga_dummy
from toga_dummy.utils import (
assert_action_not_performed,
assert_action_performed,
Expand Down Expand Up @@ -351,8 +350,8 @@ def test_as_image(window):
"""A window can be captured as an image"""
image = window.as_image()
assert_action_performed(window, "get image data")
path = Path(toga_dummy.__file__).parent / "resources/screenshot.png"
assert image.data == path.read_bytes()
# Don't need to check the raw data; just check it's the right size.
assert image.size == (318, 346)


def test_info_dialog(window, app):
Expand Down
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
"sphinx.ext.autodoc",
"sphinx.ext.napoleon",
"sphinx.ext.todo",
"sphinx_autodoc_typehints",
"sphinx_tabs.tabs",
"crate.sphinx.csv",
"sphinx_copybutton",
Expand Down Expand Up @@ -72,6 +71,7 @@
"members": True,
"undoc-members": True,
}
autodoc_typehints = "description"

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
Expand Down
Loading