allg5/alui/application.go

118 lines
2.1 KiB
Go

package alui
import (
"errors"
"github.com/spf13/afero"
"opslag.de/schobers/allg5"
"opslag.de/schobers/fs/vfs"
"opslag.de/schobers/geom"
)
type Application struct {
disp *allg5.Display
eq *allg5.EventQueue
dirs map[string]vfs.CopyDir
}
func NewApplication(size geom.Point, dispOptions allg5.NewDisplayOptions) (*Application, error) {
var init = allg5.InitAll
init.Audio = false
err := allg5.Init(init)
if err != nil {
return nil, err
}
app := &Application{}
disp, err := allg5.NewDisplay(size.X, size.Y, dispOptions)
if err != nil {
return nil, err
}
app.disp = disp
eq, err := allg5.NewEventQueue()
if err != nil {
app.Destroy()
return nil, err
}
app.eq = eq
eq.RegisterDisplay(disp)
eq.RegisterKeyboard()
eq.RegisterMouse()
return app, nil
}
func (a *Application) Destroy() {
a.disp.Destroy()
a.eq.Destroy()
if a.dirs != nil {
for _, dir := range a.dirs {
dir.Destroy()
}
}
}
func (a *Application) AddDir(path string, backup afero.Fs) (vfs.CopyDir, error) {
fs := vfs.NewOsFsFallback(path, backup)
copy, err := vfs.NewCopyDir(fs)
if err != nil {
return nil, err
}
if a.dirs == nil {
a.dirs = map[string]vfs.CopyDir{}
}
a.dirs[path] = copy
return copy, nil
}
func (a *Application) UseFile(dir, name string, use func(string) error) error {
if a.dirs == nil {
return errors.New(`no directories available`)
}
resources, ok := a.dirs[dir]
if !ok {
return errors.New(`direct not found`)
}
path, err := resources.Retrieve(name)
if err != nil {
return err
}
return use(path)
}
func (a *Application) Run(main Control, init func(*UI) error) error {
disp := a.disp
eq := a.eq
ui := NewUI(disp, main)
defer ui.Destroy()
err := init(ui)
if err != nil {
return err
}
ctx := ui.Context()
for {
allg5.ClearToColor(ctx.Palette.Icon)
ui.Render()
disp.Flip()
e := eq.Get()
for e != nil {
switch e := e.(type) {
case *allg5.DisplayCloseEvent:
return nil
case *allg5.KeyCharEvent:
if e.KeyCode == allg5.KeyF4 && e.Modifiers&allg5.KeyModAlt != 0 {
return nil
}
}
ui.Handle(e)
e = eq.Get()
}
}
}