allg5/alui/application.go

125 lines
2.2 KiB
Go
Raw Normal View History

2020-03-28 09:50:40 +00:00
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 {
2020-04-10 09:00:27 +00:00
allg5.ClearToColor(ctx.Palette.Background)
2020-03-28 09:50:40 +00:00
ui.Render()
disp.Flip()
2020-04-10 09:00:27 +00:00
if ctx.quit {
return nil
}
2020-03-28 09:50:40 +00:00
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)
2020-04-10 09:00:27 +00:00
if ctx.quit {
return nil
}
2020-03-28 09:50:40 +00:00
e = eq.Get()
}
}
}