ephemeral-garden/ui/api.go

66 lines
1.3 KiB
Go

package api
import (
"cwtch.im/tapir"
"cwtch.im/tapir/applications"
"encoding/json"
"github.com/therecipe/qt/core"
"github.com/therecipe/qt/qml"
"sync"
)
type GardenAPI struct {
applications.AuthApp
connection tapir.Connection
core.QObject
lock sync.Mutex
QMLEngine *qml.QQmlApplicationEngine
Translator *core.QTranslator
_ func(x int, y int) `signal:"DrawEvent"`
_ func(x int, y int) `signal:"newDrawEvent,auto"`
}
func (ea *GardenAPI) newDrawEvent(x int, y int) {
event := new(UpdateEvent)
event.X = x
event.Y = y
data, _ := json.Marshal(event)
ea.lock.Lock()
defer ea.lock.Unlock()
ea.connection.Send(data)
}
// NewInstance should always return a new instantiation of the application.
func (ea *GardenAPI) NewInstance() tapir.Application {
return ea
}
// Init is run when the connection is first started.
func (ea *GardenAPI) Init(connection tapir.Connection) {
// First run the Authentication App
ea.AuthApp.Init(connection)
if connection.HasCapability(applications.AuthCapability) {
// The code for out simple application (We just send and receive "Hello"
ea.connection = connection
go ea.listen()
}
}
type UpdateEvent struct {
X int
Y int
}
func (ea *GardenAPI) listen() {
for {
data := ea.connection.Expect()
event := new(UpdateEvent)
json.Unmarshal(data, event)
ea.DrawEvent(event.X, event.Y)
}
}