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
3 changes: 3 additions & 0 deletions core/src/toga/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,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
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
26 changes: 22 additions & 4 deletions docs/reference/api/resources/images.rst
Original file line number Diff line number Diff line change
@@ -1,19 +1,27 @@
Image
=====

Graphical content of arbitrary size.

.. rst-class:: widget-support
.. csv-filter:: Availability (:ref:`Key <api-status-key>`)
:header-rows: 1
:file: ../../data/widgets_by_platform.csv
:included_cols: 4,5,6,7,8,9,10
:exclude: {0: '(?!(Image|Component)$)'}


An image is graphical content of arbitrary size.

Usage
-----

An image can be constructed from:

* A path to a file on disk;
* A blob of bytes containing image data in a known image format;
* A :any:`PIL.Image` object;
* Another :any:`toga.Image`; or
* The native platform representation of an image (see the :ref:`Notes
<native-image-rep>` section below for details).

.. code-block:: python

from pathlib import Path
Expand All @@ -40,10 +48,20 @@ Notes
* PNG and JPEG formats are guaranteed to be supported.
Other formats are available on some platforms:

- macOS: GIF, BMP, TIFF
- GTK: BMP
- macOS: GIF, BMP, TIFF
- Windows: GIF, BMP, TIFF

.. _native-image-rep:

* The native platform representations for images are:

- Android: ``android.graphics.Bitmap``
- GTK: ``GdkPixbuf``
- iOS: ``UIImage``
- macOS: ``NSImage``
- Windows: ``System.Drawing.Image``

Reference
---------

Expand Down
2 changes: 1 addition & 1 deletion docs/reference/data/widgets_by_platform.csv
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,4 @@ App Paths,Resource,:class:`~toga.paths.Paths`,A mechanism for obtaining platform
Font,Resource,:class:`~toga.Font`,A text font,|y|,|y|,|y|,|y|,|y|,,
Command,Resource,:class:`~toga.Command`,Command,|y|,|y|,|y|,,|y|,,
Icon,Resource,:class:`~toga.Icon`,"A small, square image, used to provide easily identifiable visual context to a widget.",|y|,|y|,|y|,|y|,|y|,,|b|
Image,Resource,:class:`~toga.Image`,An image,|y|,|y|,|y|,|y|,|y|,,
Image,Resource,:class:`~toga.Image`,Graphical content of arbitrary size.,|y|,|y|,|y|,|y|,|y|,,
51 changes: 37 additions & 14 deletions dummy/src/toga_dummy/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,34 +12,57 @@
import toga


# We need a dummy "internal image format" for the dummy backend It's a wrapper
# around a PIL image. We can't just use a PIL image because that will be
# interpreted *as* a PIL image.
class DummyImage:
def __init__(self, image=None):
self.raw = image
if image:
buffer = BytesIO()
self.raw.save(buffer, format="png", compress_level=0)
self.data = buffer.getvalue()
else:
self.data = b"pretend this is PNG image data"


class Image(LoggedObject):
def __init__(self, interface: toga.Image, path: Path = None, data: bytes = None):
RAW_TYPE = DummyImage

def __init__(
self,
interface: toga.Image,
path: Path = None,
data: bytes = None,
raw: BytesIO = None,
):
super().__init__()
self.interface = interface
if path:
self._action("load image file", path=path)
if path.is_file():
self._data = path.read_bytes()
with PIL.Image.open(path) as image:
self._width, self._height = image.size
self.native = DummyImage(PIL.Image.open(path))
else:
self._data = b"pretend this is PNG image data"
self._width, self._height = 60, 40
else:
self.native = DummyImage()
elif data:
self._action("load image data", data=data)
self._data = data
buffer = BytesIO(data)
with PIL.Image.open(buffer) as image:
self._width, self._height = image.size
self.native = DummyImage(PIL.Image.open(BytesIO(data)))
else:
self._action("load image from raw")
self.native = raw

def get_width(self):
return self._width
if self.native.raw is None:
return 60
return self.native.raw.size[0]

def get_height(self):
return self._height
if self.native.raw is None:
return 40
return self.native.raw.size[1]

def get_data(self):
return self._data
return self.native.data

def save(self, path):
self._action("save", path=path)
8 changes: 6 additions & 2 deletions gtk/src/toga_gtk/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,24 @@


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

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

if path:
try:
self.native = GdkPixbuf.Pixbuf.new_from_file(str(path))
except GLib.GError:
raise ValueError(f"Unable to load image from {path}")
else:
elif data:
try:
input_stream = Gio.MemoryInputStream.new_from_data(data, None)
self.native = GdkPixbuf.Pixbuf.new_from_stream(input_stream, None)
except GLib.GError:
raise ValueError("Unable to load image from data")
else:
self.native = raw

def get_width(self):
return self.native.get_width()
Expand Down
9 changes: 7 additions & 2 deletions iOS/src/toga_iOS/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,24 @@ def nsdata_to_bytes(data: NSData) -> bytes:


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

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

if path:
self.native = UIImage.imageWithContentsOfFile(str(path))
if self.native is None:
raise ValueError(f"Unable to load image from {path}")
else:
elif data:
self.native = UIImage.imageWithData(
NSData.dataWithBytes(data, length=len(data))
)
if self.native is None:
raise ValueError("Unable to load image from data")
else:
self.native = raw

self.native.retain()

def __del__(self):
Expand Down
10 changes: 10 additions & 0 deletions testbed/tests/test_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ async def test_local_image(app):
assert image.height == 72


async def test_raw_image(app):
"An image can be created from the platform's raw representation"
original = toga.Image("resources/sample.png")

image = toga.Image(original._impl.native)

assert image.width == original.width
assert image.height == original.height


async def test_bad_image_file(app):
"If a file isn't a loadable image, an error is raised"
with pytest.raises(
Expand Down
Loading
Loading