about summary refs log tree commit diff stats
path: root/keychord.lua
diff options
context:
space:
mode:
authorKartik K. Agaram <vc@akkartik.com>2022-05-14 15:09:49 -0700
committerKartik K. Agaram <vc@akkartik.com>2022-05-14 15:09:49 -0700
commit18bb4621c39204396b02fb30da5f533aae65b834 (patch)
tree5f525e2b47f80402e08dd52d537c640272edaba1 /keychord.lua
parentd55960ced007758a6df45d5010c7b4f28339e7a6 (diff)
downloadtext.love-18bb4621c39204396b02fb30da5f533aae65b834.tar.gz
draw lines by default
Freehand strokes are a special case. Let's ignore them for a bit.
Diffstat (limited to 'keychord.lua')
0 files changed, 0 insertions, 0 deletions
8' href='#n98'>98 99 100 101 102 103 104 105 106 107
package types

import (
	"log"
	"sync"
)

var nextId int = 1

type Backend interface {
	Run()
}

type Worker struct {
	Backend  Backend
	Actions  chan WorkerMessage
	Messages chan WorkerMessage
	Logger   *log.Logger

	callbacks map[int]func(msg WorkerMessage) // protected by mutex
	mutex     sync.Mutex
}

func NewWorker(logger *log.Logger) *Worker {
	return &Worker{
		Actions:   make(chan WorkerMessage, 50),
		Messages:  make(chan WorkerMessage, 50),
		Logger:    logger,
		callbacks: make(map[int]func(msg WorkerMessage)),
	}
}

func (worker *Worker) setCallback(msg WorkerMessage,
	cb func(msg WorkerMessage)) {

	msg.setId(nextId)
	nextId++

	if cb != nil {
		worker.mutex.Lock()
		worker.callbacks[msg.getId()] = cb
		worker.mutex.Unlock()
	}
}

func (worker *Worker) getCallback(msg WorkerMessage) (func(msg WorkerMessage),
	bool) {

	if msg == nil {
		return nil, false
	}
	worker.mutex.Lock()
	cb, ok := worker.callbacks[msg.getId()]
	worker.mutex.Unlock()

	return cb, ok
}

func (worker *Worker) PostAction(msg WorkerMessage,
	cb func(msg WorkerMessage)) {

	if resp := msg.InResponseTo(); resp != nil {
		worker.Logger.Printf("(ui)=> %T:%T\n", msg, resp)
	} else {
		worker.Logger.Printf("(ui)=> %T\n", msg)
	}
	worker.Actions <- msg

	worker.setCallback(msg, cb)
}

func (worker *Worker) PostMessage(msg WorkerMessage,
	cb func(msg WorkerMessage)) {

	if resp := msg.InResponseTo(); resp != nil {
		worker.Logger.Printf("->(ui) %T:%T\n", msg, resp)
	} else {
		worker.Logger.Printf("->(ui) %T\n", msg)
	}
	worker.Messages <- msg

	worker.setCallback(msg, cb)
}

func (worker *Worker) ProcessMessage(msg WorkerMessage) WorkerMessage {
	if resp := msg.InResponseTo(); resp != nil {
		worker.Logger.Printf("(ui)<= %T:%T\n", msg, resp)
	} else {
		worker.Logger.Printf("(ui)<= %T\n", msg)
	}
	if cb, ok := worker.getCallback(msg.InResponseTo()); ok {
		cb(msg)
	}
	return msg
}

func (worker *Worker) ProcessAction(msg WorkerMessage) WorkerMessage {
	if resp := msg.InResponseTo(); resp != nil {
		worker.Logger.Printf("<-(ui) %T:%T\n", msg, resp)
	} else {
		worker.Logger.Printf("<-(ui) %T\n", msg)
	}
	if cb, ok := worker.getCallback(msg.InResponseTo()); ok {
		cb(msg)
	}
	return msg
}