From 39f6476b8429079e079fa691e2bb40cdd072341b Mon Sep 17 00:00:00 2001 From: Robert Lillack Date: Sat, 29 Jun 2024 17:52:47 +0200 Subject: [PATCH] image: Fix crash when `Image` property is `nil` pointer. #18 --- ui/image_cocoa.go | 4 +++- ui/image_fltk.go | 2 +- ui/imgutils.go | 19 +++++++++++++++++++ 3 files changed, 23 insertions(+), 2 deletions(-) create mode 100644 ui/imgutils.go diff --git a/ui/image_cocoa.go b/ui/image_cocoa.go index c384cdd..1387ab7 100644 --- a/ui/image_cocoa.go +++ b/ui/image_cocoa.go @@ -65,7 +65,9 @@ func (c *Image) draw() { switch img := c.Image.(type) { case *image.RGBA: - c.ref.SetImage(img) + if img != nil { + c.ref.SetImage(img) + } default: panic(fmt.Sprintf("unsupported image type: %T", img)) } diff --git a/ui/image_fltk.go b/ui/image_fltk.go index 35296ed..00b8d33 100644 --- a/ui/image_fltk.go +++ b/ui/image_fltk.go @@ -75,7 +75,7 @@ func (c *Image) handleEvent(e goFltk.Event) bool { } func (c *Image) draw() { - if c.ref == nil { + if c.ref == nil || isImageNil(c.Image) { return } diff --git a/ui/imgutils.go b/ui/imgutils.go new file mode 100644 index 0000000..639cb2b --- /dev/null +++ b/ui/imgutils.go @@ -0,0 +1,19 @@ +package ui + +import ( + "image" + "reflect" +) + +func isImageNil(i image.Image) bool { + if i == nil { + return true + } + + switch reflect.TypeOf(i).Kind() { + case reflect.Ptr, reflect.Map, reflect.Array, reflect.Chan, reflect.Slice: + return reflect.ValueOf(i).IsNil() + } + + return false +}