summary refs log tree commit diff stats
path: root/doc/pydoc/ranger.gui.mouse_event.html
diff options
context:
space:
mode:
Diffstat (limited to 'doc/pydoc/ranger.gui.mouse_event.html')
0 files changed, 0 insertions, 0 deletions
#n61'>61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
package types

import (
	"log"
	"sync"
	"sync/atomic"
)

var lastId int64 = 1 // access via atomic

type Backend interface {
	Run()
}

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

	callbacks map[int64]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[int64]func(msg WorkerMessage)),
	}
}

func (worker *Worker) setId(msg WorkerMessage) {
	id := atomic.AddInt64(&lastId, 1)
	msg.setId(id)
}

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

	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)) {

	worker.setId(msg)

	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)) {

	worker.setId(msg)

	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
}