Skip to content

Commit

Permalink
More tweaks to avoid segfaults.
Browse files Browse the repository at this point in the history
  • Loading branch information
freakboy3742 committed Jun 16, 2023
1 parent 4dfefd2 commit 809607f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 10 deletions.
27 changes: 18 additions & 9 deletions cocoa/src/toga_cocoa/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,24 @@ class Image:
def __init__(self, interface, path=None, data=None):
self.interface = interface

if path:
self.native = NSImage.alloc().initWithContentsOfFile(str(path))
if self.native is None:
raise ValueError(f"Unable to load image from {path}")
else:
nsdata = NSData.dataWithBytes(data, length=len(data))
self.native = NSImage.alloc().initWithData(nsdata)
if self.native is None:
raise ValueError("Unable to load image from data")
try:
# We *should* be able to do a direct NSImage.alloc.init...(),
# but for some reason, this segfaults in some environments
# when loading invalid images. On iOS we can avoid this by
# using the class-level constructors; on macOS we need to
# ensure we have a valid allocated image, then try to init it.
image = NSImage.alloc().retain()
if path:
self.native = image.initWithContentsOfFile(str(path))
if self.native is None:
raise ValueError(f"Unable to load image from {path}")
else:
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")
finally:
image.release()

def get_width(self):
return self.native.size.width
Expand Down
2 changes: 1 addition & 1 deletion iOS/src/toga_iOS/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def __init__(self, interface, path=None, data=None):
self.interface = interface

if path:
self.native = UIImage.initWithContentsOfFile(str(path))
self.native = UIImage.imageWithContentsOfFile(str(path))
if self.native is None:
raise ValueError(f"Unable to load image from {path}")
else:
Expand Down

0 comments on commit 809607f

Please sign in to comment.