-
Notifications
You must be signed in to change notification settings - Fork 2
/
observer.h
95 lines (79 loc) · 2.32 KB
/
observer.h
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
/*
* Copyright (C) 2018 Mark Hills <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
/*
* Implementation of "observer pattern"
*
* There are several cases in the code where we need to notify
* when something changes (eg. to update a UI.)
*
* The use of simple function calls is problematic because it creates
* cyclical dependencies in header files, and is not sufficiently
* modular to allow the code to be re-used in a self-contained test.
*
* So, reluctantly introduce a slots and signals concept; xwax is
* getting to be quite a lot of code and structure now.
*/
#ifndef OBSERVE_H
#define OBSERVE_H
#include <assert.h>
#include "list.h"
struct event {
struct list observers;
};
struct observer {
struct list event;
void (*func)(struct observer*, void*);
};
#define EVENT_INIT(event) { \
.observers = LIST_INIT(event.observers) \
}
static inline void event_init(struct event *s)
{
list_init(&s->observers);
}
static inline void event_clear(struct event *s)
{
assert(list_empty(&s->observers));
}
/*
* Pre: observer is not watching anything
* Post: observer is watching the given event
*/
static inline void watch(struct observer *observer, struct event *sig,
void (*func)(struct observer*, void*))
{
list_add(&observer->event, &sig->observers);
observer->func = func;
}
static inline void ignore(struct observer *observer)
{
list_del(&observer->event);
}
/*
* Call the callback in all slots which are watching the given event
*/
static inline void fire(struct event *s, void *data)
{
struct observer *t;
list_for_each(t, &s->observers, event) {
assert(t->func != NULL);
t->func(t, data);
}
}
#endif