source: src/Patterns/Observer.hpp@ 6d574a

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 6d574a was cd5047, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Added Logging capabilities to Observer Framework

  • Property mode set to 100644
File size: 7.9 KB
Line 
1/*
2 * Observer.hpp
3 *
4 * Created on: Jan 19, 2010
5 * Author: crueger
6 */
7
8#ifndef OBSERVER_HPP_
9#define OBSERVER_HPP_
10
11#include <map>
12#include <set>
13#include <string>
14#include <sstream>
15
16/**
17 * Basic structure for the observer pattern
18 *
19 * Observers register themselves with the observables to be notified when something changes.
20 * In the Observable code that changes, attributes should be started with OBSERVE;. This macro
21 * locks the observer mechanism while changes are done. At the end of the scope in which the
22 * macro was placed the lock is released. When the last lock is released all changes are
23 * propagated to the observers.
24 *
25 * Each observerable can have sub-observables. When one of these sub-observables changes and
26 * notifies its observers the observable that contains them will also notify its observers.
27 * This passing on of updates is blocked, when the main-observable is in the process of
28 * updating many of its internal sub-observables. This means the update is not passed, if
29 * it is produced while the main-observable itself is within any Observation block.
30 */
31
32// Deactivate any logging when we are not in debug mode
33#ifdef NDEBUG
34#undef LOG_OBSERVER
35#endif
36
37class Observable;
38class Notification;
39
40// Pointers to notifications are used for unique identification
41// using this typedef makes it hard for others to mess up this
42// identification process
43typedef Notification *const Notification_ptr;
44
45template<class _Set>
46class ObservedIterator;
47
48/**
49 * An Observer is notified by all Observed objects, when anything changes.
50 *
51 * If a simple change is done to an Object the Obervable will call the update() method
52 * of all signed on observers, passing itself as a parameter for identification. The
53 * Observers should then react to the changes and update themselves accordingly.
54 *
55 * If an observed Object is destroyed it will call the subjectKilled() method
56 * of all signed on Observers, again passing itself as a parameter for identification.
57 * The Observers should handle the destruction of an observed Object gracefully, i.e.
58 * set themselves inactive, display something else, etc. There is no need
59 * to sign of from the dying object, since this will be handled by the Observable destructor.
60 */
61class Observer
62{
63 friend class Observable;
64 friend class Notification;
65 template<class> friend class ObservedIterator;
66
67 // indicates the constructor called from Observables
68 struct BaseConstructor{};
69
70public:
71 Observer(BaseConstructor);
72 Observer(std::string);
73 virtual ~Observer();
74
75protected:
76 /**
77 * This method is called upon changes of the Observable
78 */
79 virtual void update(Observable *publisher)=0;
80
81 /**
82 * This method is called when a special named change
83 * of the Observable occured
84 */
85 virtual void recieveNotification(Observable *publisher, Notification_ptr notification);
86
87 /**
88 * This method is called when the observed object is destroyed.
89 */
90 virtual void subjectKilled(Observable *publisher)=0;
91};
92
93/**
94 * An Observable implements all neccessary method for being observed.
95 *
96 * That is, it provides methods for signing on and of from an
97 * Observable that can be used by any observer. The actual
98 * observer-mechanism is handled at a central static place
99 * to avoid memory issues when many observable are around but only few
100 * are actually observed.
101 */
102class Observable : public Observer {
103public:
104 Observable(std::string _name);
105 virtual ~Observable();
106
107 /**
108 * Sign an Observer on to this Observable. The Observer will be notified
109 * whenever something inside the Observable changes. The Observer can
110 * assign itself a priority for the changes in the range of -20:+20.
111 * The Observer with lower priority will be called before the others,
112 * same as with Unix nice-levels. This can be used when an Object
113 * contains other objects that observe it (derived values), and these objects have
114 * to recalculate their states before the changes should be propageted to the
115 * UI. A default priority of 0 should be fine in most cases, since there is
116 * ussually no need to order the update sequence.
117 */
118 virtual void signOn(Observer *target, int priority=0);
119
120 /**
121 * Sign of a previously signed on Observer. After this no more
122 * updates will be recieved from that observer.
123 */
124 virtual void signOff(Observer *target);
125
126 /**
127 * Sign on for specialized notifications
128 */
129 virtual void signOn(Observer *target, Notification_ptr notification);
130
131 /**
132 * Stop receiving a specialized notification
133 */
134 virtual void signOff(Observer *target, Notification_ptr notification);
135
136 /**
137 * Ask an Observer if it is currently in a blocked state, i.e. if
138 * Changes are in Progress, that are not yet published.
139 */
140 virtual bool isBlocked();
141
142protected:
143 virtual void update(Observable *publisher);
144 virtual void subjectKilled(Observable *publisher);
145
146 virtual void notifyAll();
147protected:
148// Observer mechanism is done from a static central place
149 /**
150 * Internal method.
151 * Do not call directly. Use OBSERVE macro instead
152 */
153 static void start_observer_internal(Observable *publisher);
154 /**
155 * Internal method.
156 * Do not call directly. Use OBSERVE macro instead
157 */
158 static void finish_observer_internal(Observable *publisher);
159
160 static void enque_notification_internal(Observable *publisher, Notification_ptr notification);
161
162private:
163 typedef std::multimap<int,Observer*> callees_t;
164 typedef std::set<Notification*> notificationSet;
165 static std::map<Observable*, int> depth;
166 static std::map<Observable*,callees_t> callTable;
167 static std::map<Observable*,notificationSet> notifications;
168 static std::set<Observable*> busyObservables;
169
170 //! @cond
171 // Structure for RAII-Style notification
172protected:
173 /**
174 * This structure implements the Observer-mechanism RAII-Idiom.
175 * It triggers certain functions on creation and destruction so that
176 * Observer mechanisms can be linked to scope block.
177 */
178 class _Observable_protector {
179 public:
180 _Observable_protector(Observable *);
181 _Observable_protector(const _Observable_protector&);
182 ~_Observable_protector();
183 private:
184 Observable *protege;
185 };
186 //! @endcond
187};
188
189class Notification {
190 friend class Observable;
191public:
192 Notification(Observable *_owner);
193 virtual ~Notification();
194protected:
195
196 void addObserver(Observer *target);
197 void removeObserver(Observer *target);
198
199 void notifyAll();
200private:
201 Observable * const owner;
202 std::set<Observer*> targets;
203};
204
205#ifdef LOG_OBSERVER
206
207/**
208 * This class is used to log the working of the observer mechanism
209 *
210 * TODO: make this conditional dependent on compiler Flag.
211 */
212class ObserverLog{
213 friend class Observable;
214 friend class Observer;
215 template <typename> friend class Cacheable;
216public:
217 ObserverLog();
218 ~ObserverLog();
219 std::string getLog(); // get everything that has been logged
220 std::string getName(void*); // get the name of an actor
221 bool isObservable(void*);
222private:
223 int count; // number to reference each actor in this framework
224 std::map<void*,std::string> names; // List of names assigned to actors
225 std::set<void*> observables; // List of pointers to Observables. Needed to distinguish Observers and Observables
226 void addName(void*, std::string); // Assign a name to an Actor
227 void addObservable(void*);
228 void deleteName(void*); // delete the name of an Actor
229 void deleteObservable(void*);
230 std::stringstream &addMessage(int depth=0); // Add a Message to the logging
231 std::stringstream log; // The internal log object
232};
233
234ObserverLog &observerLog();
235
236#endif
237
238// extra macro is necessary to work with __LINE__
239#define PASTE(a,b) PASTE_HELPER(a,b)
240#define PASTE_HELPER(a,b) a ## b
241#define OBSERVE Observable::_Observable_protector PASTE(_scope_obs_protector_,__LINE__)(this)
242#define NOTIFY(notification) do{Observable::enque_notification_internal(this,notification);}while(0)
243
244#endif /* OBSERVER_HPP_ */
Note: See TracBrowser for help on using the repository browser.