~sircmpwn/aerc

ref: 7d1770754ff432b0c6f153c066e4c749683b563f aerc/worker/types/worker.go -rw-r--r-- 2.2 KiB
7d177075Drew DeVault Add date to message viewer 1 year, 3 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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
package types

import (
	"log"
	"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

	actionCallbacks  map[int64]func(msg WorkerMessage)
	messageCallbacks map[int64]func(msg WorkerMessage)
}

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

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

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

	if cb != nil {
		worker.actionCallbacks[msg.getId()] = 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

	if cb != nil {
		worker.messageCallbacks[msg.getId()] = 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 inResponseTo := msg.InResponseTo(); inResponseTo != nil {
		if f, ok := worker.actionCallbacks[inResponseTo.getId()]; ok {
			f(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 inResponseTo := msg.InResponseTo(); inResponseTo != nil {
		if f, ok := worker.messageCallbacks[inResponseTo.getId()]; ok {
			f(msg)
		}
	}
	return msg
}