source: src/Patterns/Observer.hpp@ fa0b18

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 fa0b18 was 61ea5b, checked in by Tillmann Crueger <crueger@…>, 14 years ago

Added a macro that allows locking observer from outside of the observer

  • Property mode set to 100644
File size: 8.0 KB
RevLine 
[63c1f6]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>
[cd5047]13#include <string>
14#include <sstream>
[63c1f6]15
16/**
17 * Basic structure for the observer pattern
18 *
19 * Observers register themselves with the observables to be notified when something changes.
[c296c2]20 * In the Observable code that changes, attributes should be started with OBSERVE;. This macro
[317df8]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.
[f721c6]24 *
[63c1f6]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
[cd5047]32// Deactivate any logging when we are not in debug mode
33#ifdef NDEBUG
34#undef LOG_OBSERVER
35#endif
36
[63c1f6]37class Observable;
[ccacba]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;
[63c1f6]44
[bd58fb]45template<class _Set>
46class ObservedIterator;
[63c1f6]47
[dbb474]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 */
[63c1f6]61class Observer
62{
[d5f216]63 friend class Observable;
[ccacba]64 friend class Notification;
[bd58fb]65 template<class> friend class ObservedIterator;
[a7b761b]66
[cd5047]67 // indicates the constructor called from Observables
68 struct BaseConstructor{};
69
[63c1f6]70public:
[cd5047]71 Observer(BaseConstructor);
72 Observer(std::string);
[63c1f6]73 virtual ~Observer();
74
[d5f216]75protected:
[dbb474]76 /**
77 * This method is called upon changes of the Observable
78 */
[63c1f6]79 virtual void update(Observable *publisher)=0;
[dbb474]80
[ccacba]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
[dbb474]87 /**
88 * This method is called when the observed object is destroyed.
89 */
[63c1f6]90 virtual void subjectKilled(Observable *publisher)=0;
91};
92
[dbb474]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 */
[63c1f6]102class Observable : public Observer {
103public:
[cd5047]104 Observable(std::string _name);
[63c1f6]105 virtual ~Observable();
106
[dbb474]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 */
[0c1d97]118 virtual void signOn(Observer *target, int priority=0);
[dbb474]119
120 /**
121 * Sign of a previously signed on Observer. After this no more
122 * updates will be recieved from that observer.
123 */
[63c1f6]124 virtual void signOff(Observer *target);
125
[ccacba]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
[4fb5a3]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
[d5f216]142protected:
[63c1f6]143 virtual void update(Observable *publisher);
144 virtual void subjectKilled(Observable *publisher);
145
146 virtual void notifyAll();
147protected:
[d5f216]148// Observer mechanism is done from a static central place
[63c1f6]149 /**
150 * Internal method.
[317df8]151 * Do not call directly. Use OBSERVE macro instead
[63c1f6]152 */
153 static void start_observer_internal(Observable *publisher);
154 /**
155 * Internal method.
[317df8]156 * Do not call directly. Use OBSERVE macro instead
[63c1f6]157 */
158 static void finish_observer_internal(Observable *publisher);
159
[ccacba]160 static void enque_notification_internal(Observable *publisher, Notification_ptr notification);
161
[63c1f6]162private:
[0c1d97]163 typedef std::multimap<int,Observer*> callees_t;
[ccacba]164 typedef std::set<Notification*> notificationSet;
[63c1f6]165 static std::map<Observable*, int> depth;
[033a05]166 static std::map<Observable*,callees_t> callTable;
[ccacba]167 static std::map<Observable*,notificationSet> notifications;
[63c1f6]168 static std::set<Observable*> busyObservables;
169
[4fb5a3]170 //! @cond
[317df8]171 // Structure for RAII-Style notification
[61ea5b]172public:
[dbb474]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 */
[317df8]178 class _Observable_protector {
179 public:
180 _Observable_protector(Observable *);
[bd58fb]181 _Observable_protector(const _Observable_protector&);
[317df8]182 ~_Observable_protector();
183 private:
184 Observable *protege;
185 };
[4fb5a3]186 //! @endcond
[317df8]187};
[63c1f6]188
[ccacba]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
[cd5047]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
[50fc88c]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)
[ccacba]242#define NOTIFY(notification) do{Observable::enque_notification_internal(this,notification);}while(0)
[61ea5b]243#define LOCK_OBSERVABLE(observer) Observable::_Observable_protector PASTE(_scope_obs_protector_,__LINE__)(&(observer))
[ccacba]244
[63c1f6]245#endif /* OBSERVER_HPP_ */
Note: See TracBrowser for help on using the repository browser.