Make actions track their active contexts.

This commit is contained in:
Sam Rose 2019-07-23 11:14:48 +01:00
parent 66d13cf51e
commit 79161ce5df
2 changed files with 54 additions and 6 deletions

View File

@ -1,10 +1,61 @@
package streamdeck
import (
"context"
sdcontext "github.com/samwho/streamdeck/context"
)
type Action struct {
uuid string
handlers map[string][]EventHandler
contexts map[string]context.Context
}
func newAction(uuid string) *Action {
action := &Action{
uuid: uuid,
handlers: make(map[string][]EventHandler),
contexts: make(map[string]context.Context),
}
action.RegisterHandler(WillAppear, func(ctx context.Context, client *Client, event Event) error {
action.addContext(ctx)
return nil
})
action.RegisterHandler(WillDisappear, func(ctx context.Context, client *Client, event Event) error {
action.removeContext(ctx)
return nil
})
return action
}
func (action *Action) RegisterHandler(eventName string, handler EventHandler) {
action.handlers[eventName] = append(action.handlers[eventName], handler)
}
func (action *Action) Contexts() []context.Context {
cs := make([]context.Context, len(action.contexts))
for _, c := range action.contexts {
cs = append(cs, c)
}
return cs
}
func (action *Action) addContext(ctx context.Context) {
if sdcontext.Context(ctx) == "" {
panic("passed non-streamdeck context to addContext")
}
action.contexts[sdcontext.Context(ctx)] = ctx
}
func (action *Action) removeContext(ctx context.Context) {
if sdcontext.Context(ctx) == "" {
panic("passed non-streamdeck context to addContext")
}
delete(action.contexts, sdcontext.Context(ctx))
}

View File

@ -36,10 +36,7 @@ func NewClient(ctx context.Context, params RegistrationParams) *Client {
func (client *Client) Action(uuid string) *Action {
_, ok := client.actions[uuid]
if !ok {
client.actions[uuid] = &Action{
uuid: uuid,
handlers: make(map[string][]EventHandler),
}
client.actions[uuid] = newAction(uuid)
}
return client.actions[uuid]
}
@ -99,8 +96,8 @@ func (client *Client) Run() error {
action, ok := client.actions[event.Action]
if !ok {
log.Printf("received event for nonexistent action: %v\n", event.Action)
continue
action = client.Action(event.Action)
action.addContext(ctx)
}
for _, f := range action.handlers[event.Event] {