blob: ef45269ed6e60ea3b4a63342ca474318c6521906 [file] [log] [blame]
James Robinson646469d2014-10-03 15:33:28 -07001// Copyright (c) 2011 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef BASE_OBSERVER_LIST_H__
6#define BASE_OBSERVER_LIST_H__
7
8#include <algorithm>
9#include <limits>
10#include <vector>
11
12#include "base/basictypes.h"
13#include "base/logging.h"
14#include "base/memory/weak_ptr.h"
15
16///////////////////////////////////////////////////////////////////////////////
17//
18// OVERVIEW:
19//
20// A container for a list of observers. Unlike a normal STL vector or list,
21// this container can be modified during iteration without invalidating the
22// iterator. So, it safely handles the case of an observer removing itself
23// or other observers from the list while observers are being notified.
24//
25// TYPICAL USAGE:
26//
27// class MyWidget {
28// public:
29// ...
30//
31// class Observer {
32// public:
33// virtual void OnFoo(MyWidget* w) = 0;
34// virtual void OnBar(MyWidget* w, int x, int y) = 0;
35// };
36//
37// void AddObserver(Observer* obs) {
38// observer_list_.AddObserver(obs);
39// }
40//
41// void RemoveObserver(Observer* obs) {
42// observer_list_.RemoveObserver(obs);
43// }
44//
45// void NotifyFoo() {
46// FOR_EACH_OBSERVER(Observer, observer_list_, OnFoo(this));
47// }
48//
49// void NotifyBar(int x, int y) {
50// FOR_EACH_OBSERVER(Observer, observer_list_, OnBar(this, x, y));
51// }
52//
53// private:
54// ObserverList<Observer> observer_list_;
55// };
56//
57//
58///////////////////////////////////////////////////////////////////////////////
59
60template <typename ObserverType>
61class ObserverListThreadSafe;
62
63template <class ObserverType>
64class ObserverListBase
65 : public base::SupportsWeakPtr<ObserverListBase<ObserverType> > {
66 public:
67 // Enumeration of which observers are notified.
68 enum NotificationType {
69 // Specifies that any observers added during notification are notified.
70 // This is the default type if non type is provided to the constructor.
71 NOTIFY_ALL,
72
73 // Specifies that observers added while sending out notification are not
74 // notified.
75 NOTIFY_EXISTING_ONLY
76 };
77
78 // An iterator class that can be used to access the list of observers. See
79 // also the FOR_EACH_OBSERVER macro defined below.
80 class Iterator {
81 public:
82 Iterator(ObserverListBase<ObserverType>& list);
83 ~Iterator();
84 ObserverType* GetNext();
85
86 private:
87 base::WeakPtr<ObserverListBase<ObserverType> > list_;
88 size_t index_;
89 size_t max_index_;
90 };
91
92 ObserverListBase() : notify_depth_(0), type_(NOTIFY_ALL) {}
93 explicit ObserverListBase(NotificationType type)
94 : notify_depth_(0), type_(type) {}
95
96 // Add an observer to the list. An observer should not be added to
97 // the same list more than once.
98 void AddObserver(ObserverType* obs);
99
100 // Remove an observer from the list if it is in the list.
101 void RemoveObserver(ObserverType* obs);
102
James Robinson6e9a1c92014-11-13 17:05:42 -0800103 // Determine whether a particular observer is in the list.
104 bool HasObserver(const ObserverType* observer) const;
James Robinson646469d2014-10-03 15:33:28 -0700105
106 void Clear();
107
108 protected:
109 size_t size() const { return observers_.size(); }
110
111 void Compact();
112
113 private:
114 friend class ObserverListThreadSafe<ObserverType>;
115
116 typedef std::vector<ObserverType*> ListType;
117
118 ListType observers_;
119 int notify_depth_;
120 NotificationType type_;
121
122 friend class ObserverListBase::Iterator;
123
124 DISALLOW_COPY_AND_ASSIGN(ObserverListBase);
125};
126
127template <class ObserverType>
128ObserverListBase<ObserverType>::Iterator::Iterator(
129 ObserverListBase<ObserverType>& list)
130 : list_(list.AsWeakPtr()),
131 index_(0),
132 max_index_(list.type_ == NOTIFY_ALL ?
133 std::numeric_limits<size_t>::max() :
134 list.observers_.size()) {
135 ++list_->notify_depth_;
136}
137
138template <class ObserverType>
139ObserverListBase<ObserverType>::Iterator::~Iterator() {
140 if (list_.get() && --list_->notify_depth_ == 0)
141 list_->Compact();
142}
143
144template <class ObserverType>
145ObserverType* ObserverListBase<ObserverType>::Iterator::GetNext() {
146 if (!list_.get())
147 return NULL;
148 ListType& observers = list_->observers_;
149 // Advance if the current element is null
150 size_t max_index = std::min(max_index_, observers.size());
151 while (index_ < max_index && !observers[index_])
152 ++index_;
153 return index_ < max_index ? observers[index_++] : NULL;
154}
155
156template <class ObserverType>
157void ObserverListBase<ObserverType>::AddObserver(ObserverType* obs) {
158 if (std::find(observers_.begin(), observers_.end(), obs)
159 != observers_.end()) {
160 NOTREACHED() << "Observers can only be added once!";
161 return;
162 }
163 observers_.push_back(obs);
164}
165
166template <class ObserverType>
167void ObserverListBase<ObserverType>::RemoveObserver(ObserverType* obs) {
168 typename ListType::iterator it =
169 std::find(observers_.begin(), observers_.end(), obs);
170 if (it != observers_.end()) {
171 if (notify_depth_) {
172 *it = 0;
173 } else {
174 observers_.erase(it);
175 }
176 }
177}
178
179template <class ObserverType>
James Robinson6e9a1c92014-11-13 17:05:42 -0800180bool ObserverListBase<ObserverType>::HasObserver(
181 const ObserverType* observer) const {
James Robinson646469d2014-10-03 15:33:28 -0700182 for (size_t i = 0; i < observers_.size(); ++i) {
183 if (observers_[i] == observer)
184 return true;
185 }
186 return false;
187}
188
189template <class ObserverType>
190void ObserverListBase<ObserverType>::Clear() {
191 if (notify_depth_) {
192 for (typename ListType::iterator it = observers_.begin();
193 it != observers_.end(); ++it) {
194 *it = 0;
195 }
196 } else {
197 observers_.clear();
198 }
199}
200
201template <class ObserverType>
202void ObserverListBase<ObserverType>::Compact() {
203 observers_.erase(
204 std::remove(observers_.begin(), observers_.end(),
205 static_cast<ObserverType*>(NULL)), observers_.end());
206}
207
208template <class ObserverType, bool check_empty = false>
209class ObserverList : public ObserverListBase<ObserverType> {
210 public:
211 typedef typename ObserverListBase<ObserverType>::NotificationType
212 NotificationType;
213
214 ObserverList() {}
215 explicit ObserverList(NotificationType type)
216 : ObserverListBase<ObserverType>(type) {}
217
218 ~ObserverList() {
219 // When check_empty is true, assert that the list is empty on destruction.
220 if (check_empty) {
221 ObserverListBase<ObserverType>::Compact();
222 DCHECK_EQ(ObserverListBase<ObserverType>::size(), 0U);
223 }
224 }
225
226 bool might_have_observers() const {
227 return ObserverListBase<ObserverType>::size() != 0;
228 }
229};
230
231#define FOR_EACH_OBSERVER(ObserverType, observer_list, func) \
232 do { \
233 if ((observer_list).might_have_observers()) { \
234 ObserverListBase<ObserverType>::Iterator \
235 it_inside_observer_macro(observer_list); \
236 ObserverType* obs; \
237 while ((obs = it_inside_observer_macro.GetNext()) != NULL) \
238 obs->func; \
239 } \
240 } while (0)
241
242#endif // BASE_OBSERVER_LIST_H__