source: src/CodePatterns/Observer/Observable.hpp@ 084729c

Action_Thermostats Add_AtomRandomPerturbation Add_RotateAroundBondAction Add_SelectAtomByNameAction Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_StructOpt_integration_tests Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_ChronosMutex Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion GeometryObjects Gui_displays_atomic_force_velocity IndependentFragmentGrids_IntegrationTest JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks RotateToPrincipalAxisSystem_UndoRedo StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg ThirdParty_MPQC_rebuilt_buildsystem TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps Ubuntu_1604_changes stable
Last change on this file since 084729c was 084729c, checked in by Frederik Heber <heber@…>, 8 years ago

Squashed 'ThirdParty/CodePatterns/' content from commit c1e1041

git-subtree-dir: ThirdParty/CodePatterns
git-subtree-split: c1e10418c454f98be2f43d93167642b0008428fc

  • Property mode set to 100644
File size: 6.3 KB
Line 
1/*
2 * Observable.hpp
3 *
4 * Created on: Dec 1, 2011
5 * Author: heber
6 */
7
8#ifndef OBSERVABLE_HPP_
9#define OBSERVABLE_HPP_
10
11// include config.h
12#ifdef HAVE_CONFIG_H
13#include <config.h>
14#endif
15
16#include <map>
17#include <set>
18#include <string>
19#include <boost/function.hpp>
20
21#include "CodePatterns/Range.hpp"
22#include "CodePatterns/Observer/defs.hpp"
23#include "CodePatterns/Observer/GlobalObservableInfo.hpp"
24#include "CodePatterns/Observer/Observer.hpp"
25
26class Graveyard;
27class scoped_lock;
28
29/**
30 * An Observable implements all neccessary method for being observed.
31 *
32 * That is, it provides methods for signing on and of from an
33 * Observable that can be used by any observer. The actual
34 * observer-mechanism is handled at a central static place
35 * to avoid memory issues when many observable are around but only few
36 * are actually observed.
37 *
38 * \note We have to clean our Channels from static NotificationChannels and
39 * we call Channels::subjectKilled() to let Observers that have only signed
40 * on to single channel still know when their observable has died.
41 *
42 * Note that one may allow an Observable to live some over-time by using
43 * the Graveyard. This allows any Observer to still access the instance
44 * in order to properly sign off. It is destroyed when no Observer is left.
45 */
46class Observable : public Observer {
47 //!> grant Relay access to NotificationChannels as we know it uses the mutex as well
48 friend class Relay;
49public:
50 //!> typedef for a vector of channels
51 typedef std::vector<size_t> channels_t;
52
53 Observable(
54 std::string _name,
55 const channels_t &_channels = channels_t());
56 virtual ~Observable();
57
58private:
59 /** Helper class to create a unique increasing list.
60 *
61 */
62 struct UniqueNumber
63 {
64 int operator()()
65 { return value++; }
66 int value;
67 };
68
69public:
70 static channels_t getChannelList(const size_t max);
71
72 /**
73 * Sign an Observer on to this Observable. The Observer will be notified
74 * whenever something inside the Observable changes. The Observer can
75 * assign itself a priority for the changes in the range of -20:+20.
76 * The Observer with lower priority will be called before the others,
77 * same as with Unix nice-levels. This can be used when an Object
78 * contains other objects that observe it (derived values), and these objects have
79 * to recalculate their states before the changes should be propageted to the
80 * UI. A default priority of 0 should be fine in most cases, since there is
81 * ussually no need to order the update sequence.
82 */
83 virtual void signOn(
84 Observer * target,
85 GlobalObservableInfo::PriorityLevel priority = GlobalObservableInfo::PriorityDefault) const;
86
87 /**
88 * Sign of a previously signed on Observer. After this no more
89 * updates will be recieved from that observer.
90 */
91 virtual void signOff(Observer *target) const;
92
93 /**
94 * Sign on for specialized notifications
95 */
96 virtual void signOn(
97 Observer *target,
98 size_t channelno,
99 GlobalObservableInfo::PriorityLevel priority =
100 GlobalObservableInfo::PriorityDefault) const;
101
102 /**
103 * Stop receiving a specialized notification
104 */
105 virtual void signOff(Observer *target, size_t channelno) const;
106
107 /**
108 * Ask an Observer if it is currently in a blocked state, i.e. if
109 * Changes are in Progress, that are not yet published.
110 */
111 virtual bool isBlocked() const;
112
113 Notification_ptr getChannel(size_t no) const;
114
115 size_t getNumberOfObservers() const;
116
117protected:
118 virtual void update(Observable *publisher);
119 virtual void subjectKilled(Observable *publisher);
120
121 virtual void notifyAll();
122protected:
123// Observer mechanism is done from a static central place
124 /**
125 * Internal method.
126 * Do not call directly. Use OBSERVE macro instead
127 */
128 static void start_observer_internal(Observable *publisher);
129 /**
130 * Internal method.
131 * Do not call directly. Use OBSERVE macro instead
132 */
133 static void finish_observer_internal(Observable *publisher);
134
135 static void enque_notification_internal(Observable *publisher, Notification_ptr notification);
136
137protected:
138
139 static void insertNotificationChannel( std::pair<Observable*, Channels *> _pair);
140 static void eraseNotificationChannel(Observable * const _target);
141 static bool isNotificationChannelPresent(const Observable * const _target);
142 static const Channels *getNotificationChannels(const Observable * const _target);
143 static Notification_ptr getNotificationChannel(const Observable * const _target, const size_t _no);
144
145private:
146
147 typedef std::map<Observable*, Channels *> ChannelMap;
148 static ChannelMap NotificationChannels;
149
150private:
151 friend class Zombie;
152 friend class Graveyard;
153
154 typedef boost::function<void (const Observable*)> graveyard_informer_t;
155
156 /** Bound function to call when Observer are signing off (needs to be a ptr
157 * as we must be able to rebound it.
158 *
159 * \warning Do not delete this pointer, the instance is either a static one
160 * or handled someplace else (e.g. in the Graveyard).
161 */
162 graveyard_informer_t * graveyard_informer;
163
164 //!> default informer that does nothing
165 static graveyard_informer_t noop_informer;
166
167 /** Sets the bound function for over-time life-time management.
168 *
169 * \param _graveyard ptr Graveyard to inform of leaving Observers
170 */
171 void setGraveyardInformer(graveyard_informer_t * _graveyard_informer)
172 {
173 graveyard_informer = _graveyard_informer;
174 }
175
176 //! @cond
177 // Structure for RAII-Style notification
178public:
179 /**
180 * This structure implements the Observer-mechanism RAII-Idiom.
181 * It triggers certain functions on creation and destruction so that
182 * Observer mechanisms can be linked to scope block.
183 */
184 class _Observable_protector {
185 public:
186 _Observable_protector(Observable *);
187 _Observable_protector(const _Observable_protector&);
188 ~_Observable_protector();
189 private:
190 Observable *protege;
191 };
192 //! @endcond
193};
194
195
196// extra macro is necessary to work with __LINE__
197#define PASTE(a,b) PASTE_HELPER(a,b)
198#define PASTE_HELPER(a,b) a ## b
199#define OBSERVE Observable::_Observable_protector PASTE(_scope_obs_protector_,__LINE__)(this)
200#define NOTIFY(channelno) do{Observable::enque_notification_internal(this,Observable::getNotificationChannel(this,channelno));}while(0)
201#define LOCK_OBSERVABLE(observable) Observable::_Observable_protector PASTE(_scope_obs_protector_,__LINE__)(&(observable))
202
203#endif /* OBSERVABLE_HPP_ */
Note: See TracBrowser for help on using the repository browser.