examples/dropfile: bug fix: handle errors correctly

This commit is contained in:
Hajime Hoshi 2023-01-25 15:25:01 +09:00
parent f009dd8dd2
commit 0c76a0cbd7

View File

@ -25,48 +25,68 @@ import (
) )
type Game struct { type Game struct {
imageMutex sync.Mutex images []*ebiten.Image
images []*ebiten.Image err error
m sync.Mutex
} }
func (g *Game) Update() error { func (g *Game) Update() error {
if err := func() error {
g.m.Lock()
defer g.m.Unlock()
return g.err
}(); err != nil {
return err
}
if files := ebiten.DroppedFiles(); files != nil { if files := ebiten.DroppedFiles(); files != nil {
go fs.WalkDir(files, ".", func(path string, d fs.DirEntry, err error) error { go func() {
if err != nil { if err := fs.WalkDir(files, ".", func(path string, d fs.DirEntry, err error) error {
return err if err != nil {
} return err
}
fi, err := d.Info() fi, err := d.Info()
if err != nil { if err != nil {
return err return err
} }
log.Printf("Name: %s, Size: %d, IsDir: %t, ModTime: %v", fi.Name(), fi.Size(), fi.IsDir(), fi.ModTime()) log.Printf("Name: %s, Size: %d, IsDir: %t, ModTime: %v", fi.Name(), fi.Size(), fi.IsDir(), fi.ModTime())
f, err := files.Open(path) f, err := files.Open(path)
if err != nil { if err != nil {
return err return err
} }
defer f.Close() defer func() {
_ = f.Close()
}()
img, err := png.Decode(f)
if err != nil {
return nil
}
eimg := ebiten.NewImageFromImage(img)
g.m.Lock()
g.images = append(g.images, eimg)
g.m.Unlock()
img, err := png.Decode(f)
if err != nil {
return nil return nil
}); err != nil {
g.m.Lock()
if g.err == nil {
g.err = err
}
g.m.Unlock()
} }
eimg := ebiten.NewImageFromImage(img) }()
g.imageMutex.Lock()
g.images = append(g.images, eimg)
g.imageMutex.Unlock()
return nil
})
} }
return nil return nil
} }
func (g *Game) Draw(screen *ebiten.Image) { func (g *Game) Draw(screen *ebiten.Image) {
g.imageMutex.Lock() g.m.Lock()
defer g.imageMutex.Unlock() defer g.m.Unlock()
if len(g.images) == 0 { if len(g.images) == 0 {
ebitenutil.DebugPrint(screen, "Drop PNG files onto this window!") ebitenutil.DebugPrint(screen, "Drop PNG files onto this window!")