Skip to content

Commit

Permalink
Merge pull request #1696 from andydotxyz/fix/svgdetection
Browse files Browse the repository at this point in the history
Improve detection of SVG from resources in case name was wrong
  • Loading branch information
andydotxyz committed Dec 30, 2020
2 parents ed0eee9 + 43c8b56 commit d251eb8
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 3 deletions.
31 changes: 28 additions & 3 deletions internal/painter/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,24 @@ func PaintImage(img *canvas.Image, c fyne.Canvas, width, height int) image.Image

switch {
case img.File != "" || img.Resource != nil:
var file io.Reader
var name string
var (
file io.Reader
name string
isSVG bool
)
if img.Resource != nil {
name = img.Resource.Name()
file = bytes.NewReader(img.Resource.Content())
isSVG = isResourceSVG(img.Resource)
} else {
name = img.File
handle, _ := os.Open(img.File)
defer handle.Close()
file = handle
isSVG = isFileSVG(img.File)
}

if strings.ToLower(filepath.Ext(name)) == ".svg" {
if isSVG {
tex := svgCacheGet(name, width, height)
if tex == nil {
// Not in cache, so load the item and add to cache
Expand Down Expand Up @@ -163,3 +168,23 @@ func checkImageMinSize(img *canvas.Image, c fyne.Canvas, pixX, pixY int) bool {

return true
}

func isFileSVG(path string) bool {
return strings.ToLower(filepath.Ext(path)) == ".svg"
}

func isResourceSVG(res fyne.Resource) bool {
if strings.ToLower(filepath.Ext(res.Name())) == ".svg" {
return true
}

if len(res.Content()) < 5 {
return false
}

switch strings.ToLower(string(res.Content()[:5])) {
case "<!doc", "<?xml", "<svg ":
return true
}
return false
}
32 changes: 32 additions & 0 deletions internal/painter/image_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package painter

import (
"testing"

"github.com/stretchr/testify/assert"

"fyne.io/fyne"
)

func TestIsFileSVG(t *testing.T) {
assert.True(t, isFileSVG("test.svg"))
assert.True(t, isFileSVG("test.SVG"))
assert.False(t, isFileSVG("testsvg"))
assert.False(t, isFileSVG("test.png"))
}

func TestIsResourceSVG(t *testing.T) {
res, err := fyne.LoadResourceFromPath("./testdata/stroke.svg")
assert.Nil(t, err)
assert.True(t, isResourceSVG(res))

res.(*fyne.StaticResource).StaticName = "stroke"
assert.True(t, isResourceSVG(res))

svgString := "<svg version=\"1.1\"></svg>"
res.(*fyne.StaticResource).StaticContent = []byte(svgString)
assert.True(t, isResourceSVG(res))

res.(*fyne.StaticResource).StaticContent = []byte("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + svgString)
assert.True(t, isResourceSVG(res))
}

0 comments on commit d251eb8

Please sign in to comment.