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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_COMMON_DEPRECATED_EVENT_SYS_INL_H_
#define CHROME_COMMON_DEPRECATED_EVENT_SYS_INL_H_
#include <map>
#include "base/atomicops.h"
#include "base/basictypes.h"
#include "base/condition_variable.h"
#include "base/lock.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/port.h"
#include "chrome/common/deprecated/event_sys.h"
// How to use Channels:
// 0. Assume Bob is the name of the class from which you want to broadcast
// events.
// 1. Choose an EventType. This could be an Enum or something more complicated.
// 2. Create an EventTraits class for your EventType. It must have
// two members:
//
// typedef x EventType;
// static bool IsChannelShutdownEvent(const EventType& event);
//
// 3. Add an EventChannel<MyEventTraits>* instance and event_channel() const;
// accessor to Bob.
// Delete the channel ordinarily in Bob's destructor, or whenever you want.
// 4. To broadcast events, call bob->event_channel()->NotifyListeners(event).
// 5. Only call NotifyListeners from a single thread at a time.
// How to use Listeners/Hookups:
// 0. Assume you want a class called Lisa to listen to events from Bob.
// 1. Create an event handler method in Lisa. Its single argument should be of
// your event type.
// 2. Add a EventListenerHookup* hookup_ member to Lisa.
// 3. Initialize the hookup by calling:
//
// hookup_ = NewEventListenerHookup(bob->event_channel(),
// this,
// &Lisa::HandleEvent);
//
// 4. Delete hookup_ in Lisa's destructor, or anytime sooner to stop receiving
// events.
// An Event Channel is a source, or broadcaster of events. Listeners subscribe
// by calling the AddListener() method. The owner of the channel calls the
// NotifyListeners() method.
//
// Don't inherit from this class. Just make an event_channel member and an
// event_channel() accessor.
// No reason why CallbackWaiters has to be templatized.
class CallbackWaiters {
public:
CallbackWaiters() : waiter_count_(0),
callback_done_(false),
condvar_(&mutex_) {
}
~CallbackWaiters() {
DCHECK_EQ(0, waiter_count_);
}
void WaitForCallbackToComplete(Lock* listeners_mutex) {
{
AutoLock lock(mutex_);
waiter_count_ += 1;
listeners_mutex->Release();
while (!callback_done_)
condvar_.Wait();
waiter_count_ -= 1;
if (0 != waiter_count_)
return;
}
delete this;
}
void Signal() {
AutoLock lock(mutex_);
callback_done_ = true;
condvar_.Broadcast();
}
protected:
int waiter_count_;
bool callback_done_;
Lock mutex_;
ConditionVariable condvar_;
};
template <typename EventTraitsType, typename NotifyLock,
typename ScopedNotifyLocker>
class EventChannel {
public:
typedef EventTraitsType EventTraits;
typedef typename EventTraits::EventType EventType;
typedef EventListener<EventType> Listener;
protected:
typedef std::map<Listener*, bool> Listeners;
public:
// The shutdown event gets send in the EventChannel's destructor.
explicit EventChannel(const EventType& shutdown_event)
: current_listener_callback_(NULL),
callback_waiters_(NULL),
shutdown_event_(shutdown_event) {
}
~EventChannel() {
// Tell all the listeners that the channel is being deleted.
NotifyListeners(shutdown_event_);
// Make sure all the listeners have been disconnected. Otherwise, they
// will try to call RemoveListener() at a later date.
#if defined(DEBUG)
AutoLock lock(listeners_mutex_);
for (typename Listeners::iterator i = listeners_.begin();
i != listeners_.end(); ++i) {
DCHECK(i->second) << "Listener not disconnected";
}
#endif
}
// Never call this twice for the same listener.
//
// Thread safe.
void AddListener(Listener* listener) {
AutoLock lock(listeners_mutex_);
typename Listeners::iterator found = listeners_.find(listener);
if (found == listeners_.end()) {
listeners_.insert(std::make_pair(listener,
false)); // Not dead yet.
} else {
DCHECK(found->second) << "Attempted to add the same listener twice.";
found->second = false; // Not dead yet.
}
}
// If listener's callback is currently executing, this method waits until the
// callback completes before returning.
//
// Thread safe.
void RemoveListener(Listener* listener) {
bool wait = false;
listeners_mutex_.Acquire();
typename Listeners::iterator found = listeners_.find(listener);
if (found != listeners_.end()) {
found->second = true; // Mark as dead.
wait = (found->first == current_listener_callback_ &&
(MessageLoop::current() != current_listener_callback_message_loop_));
}
if (!wait) {
listeners_mutex_.Release();
return;
}
if (NULL == callback_waiters_)
callback_waiters_ = new CallbackWaiters;
callback_waiters_->WaitForCallbackToComplete(&listeners_mutex_);
}
// Blocks until all listeners have been notified.
//
// NOT thread safe. Must only be called by one thread at a time.
void NotifyListeners(const EventType& event) {
ScopedNotifyLocker lock_notify(notify_lock_);
listeners_mutex_.Acquire();
DCHECK(NULL == current_listener_callback_);
current_listener_callback_message_loop_ = MessageLoop::current();
typename Listeners::iterator i = listeners_.begin();
while (i != listeners_.end()) {
if (i->second) { // Clean out dead listeners
listeners_.erase(i++);
continue;
}
current_listener_callback_ = i->first;
listeners_mutex_.Release();
i->first->HandleEvent(event);
listeners_mutex_.Acquire();
current_listener_callback_ = NULL;
if (NULL != callback_waiters_) {
callback_waiters_->Signal();
callback_waiters_ = NULL;
}
++i;
}
listeners_mutex_.Release();
}
// A map iterator remains valid until the element it points to gets removed
// from the map, so a map is perfect for our needs.
//
// Map value is a bool, true means the Listener is dead.
Listeners listeners_;
// NULL means no callback is currently being called.
Listener* current_listener_callback_;
// Only valid when current_listener is not NULL.
// The thread on which the callback is executing.
MessageLoop* current_listener_callback_message_loop_;
// Win32 Event that is usually NULL. Only created when another thread calls
// Remove while in callback. Owned and closed by the thread calling Remove().
CallbackWaiters* callback_waiters_;
Lock listeners_mutex_; // Protects all members above.
const EventType shutdown_event_;
NotifyLock notify_lock_;
DISALLOW_COPY_AND_ASSIGN(EventChannel);
};
// An EventListenerHookup hooks up a method in your class to an EventChannel.
// Deleting the hookup disconnects from the EventChannel.
//
// Contains complexity of inheriting from Listener class and managing lifetimes.
//
// Create using NewEventListenerHookup() to avoid explicit template arguments.
class EventListenerHookup {
public:
virtual ~EventListenerHookup() { }
};
template <typename EventChannel, typename EventTraits,
class Derived>
class EventListenerHookupImpl : public EventListenerHookup,
public EventListener<typename EventTraits::EventType> {
public:
explicit EventListenerHookupImpl(EventChannel* channel)
: channel_(channel), deleted_(NULL) {
channel->AddListener(this);
connected_ = true;
}
~EventListenerHookupImpl() {
if (NULL != deleted_)
*deleted_ = true;
if (connected_)
channel_->RemoveListener(this);
}
typedef typename EventTraits::EventType EventType;
virtual void HandleEvent(const EventType& event) {
DCHECK(connected_);
bool deleted = false;
deleted_ = &deleted;
static_cast<Derived*>(this)->Callback(event);
if (deleted) // The callback (legally) deleted this.
return; // The only safe thing to do.
deleted_ = NULL;
if (EventTraits::IsChannelShutdownEvent(event)) {
channel_->RemoveListener(this);
connected_ = false;
}
}
protected:
EventChannel* const channel_;
bool connected_;
bool* deleted_; // Allows the handler to delete the hookup.
};
// SimpleHookup just passes the event to the callback message.
template <typename EventChannel, typename EventTraits,
typename CallbackObject, typename CallbackMethod>
class SimpleHookup
: public EventListenerHookupImpl<EventChannel, EventTraits,
SimpleHookup<EventChannel,
EventTraits,
CallbackObject,
CallbackMethod> > {
public:
SimpleHookup(EventChannel* channel, CallbackObject* cbobject,
CallbackMethod cbmethod)
: EventListenerHookupImpl<EventChannel, EventTraits,
SimpleHookup>(channel), cbobject_(cbobject),
cbmethod_(cbmethod) { }
typedef typename EventTraits::EventType EventType;
void Callback(const EventType& event) {
(cbobject_->*cbmethod_)(event);
}
CallbackObject* const cbobject_;
CallbackMethod const cbmethod_;
};
// ArgHookup also passes an additional arg to the callback method.
template <typename EventChannel, typename EventTraits,
typename CallbackObject, typename CallbackMethod,
typename CallbackArg0>
class ArgHookup
: public EventListenerHookupImpl<EventChannel, EventTraits,
ArgHookup<EventChannel, EventTraits,
CallbackObject,
CallbackMethod,
CallbackArg0> > {
public:
ArgHookup(EventChannel* channel, CallbackObject* cbobject,
CallbackMethod cbmethod, CallbackArg0 arg0)
: EventListenerHookupImpl<EventChannel, EventTraits,
ArgHookup>(channel), cbobject_(cbobject),
cbmethod_(cbmethod), arg0_(arg0) { }
typedef typename EventTraits::EventType EventType;
void Callback(const EventType& event) {
(cbobject_->*cbmethod_)(arg0_, event);
}
CallbackObject* const cbobject_;
CallbackMethod const cbmethod_;
CallbackArg0 const arg0_;
};
template <typename EventChannel, typename CallbackObject,
typename CallbackMethod>
EventListenerHookup* NewEventListenerHookup(EventChannel* channel,
CallbackObject* cbobject,
CallbackMethod cbmethod) {
return new SimpleHookup<EventChannel,
typename EventChannel::EventTraits,
CallbackObject, CallbackMethod>(channel, cbobject, cbmethod);
}
template <typename EventChannel, typename CallbackObject,
typename CallbackMethod, typename CallbackArg0>
EventListenerHookup* NewEventListenerHookup(EventChannel* channel,
CallbackObject* cbobject,
CallbackMethod cbmethod,
CallbackArg0 arg0) {
return new ArgHookup<EventChannel,
typename EventChannel::EventTraits,
CallbackObject, CallbackMethod, CallbackArg0>(channel, cbobject,
cbmethod, arg0);
}
#endif // CHROME_COMMON_DEPRECATED_EVENT_SYS_INL_H_
|