diff --git a/action.go b/action.go index af3b177..5b7e2a7 100644 --- a/action.go +++ b/action.go @@ -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)) +} diff --git a/client.go b/client.go index 0ed0674..118ff72 100644 --- a/client.go +++ b/client.go @@ -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] {