]> Creatis software - bbtk.git/blob - kernel/src/bbtkBlackBox.h
=== MAJOR RELEASE ====
[bbtk.git] / kernel / src / bbtkBlackBox.h
1 /*=========================================================================
2                                                                                 
3   Program:   bbtk
4   Module:    $RCSfile: bbtkBlackBox.h,v $
5   Language:  C++
6   Date:      $Date: 2008/04/18 12:59:15 $
7   Version:   $Revision: 1.6 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See doc/license.txt or
11   http://www.creatis.insa-lyon.fr/Public/bbtk/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18
19
20 /**
21  *  \file 
22  *  \brief Class bbtk::BlackBox : abstract black-box interface. 
23  */
24
25 /**
26  * \class bbtk::BlackBox
27  * \brief Abstract black-box interface 
28  */
29  
30 #ifndef __bbtkBlackBox_h__
31 #define __bbtkBlackBox_h__
32
33 #include "bbtkSystem.h"
34 #include "bbtkBlackBoxDescriptor.h"
35 #include "bbtkBlackBoxInputConnector.h"
36 #include "bbtkBlackBoxOutputConnector.h"
37 #include <set>
38
39 namespace bbtk
40 {
41
42   
43   struct Void { Void(int = 0) {} };
44   
45   class Factory;
46
47   class BBTK_EXPORT BlackBox : public Object
48   {
49     BBTK_ABSTRACT_OBJECT_INTERFACE(BlackBox);
50   public: 
51     //==================================================================
52     // INTERFACE
53     //==================================================================
54  
55     /// The type of map of output connector pointers
56     typedef std::map<std::string, BlackBoxOutputConnector*> 
57     OutputConnectorMapType;
58     /// The type of map of input connector pointers
59     typedef std::map<std::string, BlackBoxInputConnector*> 
60     InputConnectorMapType;
61
62     /// Returns the pointer on the descriptor of the box
63     virtual BlackBoxDescriptor::Pointer bbGetDescriptor() const = 0;
64
65     /// Returns a pointer on a clone of the box with name <name>
66     virtual BlackBox::Pointer bbClone(const std::string& name) = 0;
67
68     /// User overloadable destruction method of a black box
69     /// UNUSED FOR THE MOMENT
70     virtual void bbUserDelete();
71
72     /// Returns the Name of the Type of the BlackBox
73     const std::string& bbGetTypeName() const 
74       { return bbGetDescriptor()->GetTypeName(); }
75  
76     
77     /// Returns the name of the BlackBox (instance)
78     const std::string& bbGetName() const { return bbmName; }
79
80     /// Returns the full name of the BlackBox (instance+type)
81     virtual std::string bbGetFullName() const;
82
83     /// Returns the name with the name of the parent prepended if any
84     virtual std::string bbGetNameWithParent() const;
85     
86     /// Sets the parent of the BlackBox
87     void bbSetParent(BlackBox::Pointer p) { bbmParent = p; }
88     /// Returns the parent of the BlackBox, i.e the BlackBox that contains it (0 if none)
89     BlackBox::Pointer bbGetParent() const { return bbmParent.lock(); }
90
91
92     /// Main processing method of the box.
93     virtual void bbExecute(bool force = false);
94
95     ///  Signals that the BlackBox has been modified through the input connector c
96     /// and propagates it downward
97     virtual void bbSetModifiedStatus(BlackBoxInputConnector* c = 0);
98     /// Signals that the BlackBox outputs have been modified 
99     /// without marking the box as MODIFIED because its output state is ok. 
100     /// This method should be used by widgets in response 
101     /// to user interaction when **ALL** outputs have been modified
102     /// (after the outputs has been updated !)
103     virtual void bbSignalOutputModification(bool reaction = true);
104     ///  Signals that the BlackBox output "output_name" have been modified 
105     /// without marking the box as MODIFIED because its output state is ok. 
106     /// This method should be used by widgets in response to user interaction 
107     /// only when **ONE** output has been modified
108     /// (after the output has been updated !)
109     virtual void bbSignalOutputModification( const std::string& output_name,
110 bool reaction = true);
111     ///  Signals that the BlackBox vector of outputs "output_name" 
112     ///  have been modified 
113     /// without marking the box as MODIFIED because its output state is ok. 
114     /// This method should be used by widgets in response to user interaction 
115     /// When more than one output has been changed but not all
116     /// (after the outputs have been updated of course!)
117     virtual void bbSignalOutputModification( const std::vector<std::string>& output_name,
118 bool reaction = true);
119
120     /// Gets the status of the box
121     virtual const IOStatus& bbGetStatus() const { return bbmStatus; }
122
123
124     /// Returns true iff the BlackBox has an input of name label
125     virtual bool bbHasInput(const std::string& label) const;
126     /// Returns true iff the BlackBox has an output of name label
127     virtual bool bbHasOutput(const std::string& label) const;
128
129     ///  Gets the input type of a given label
130     virtual TypeInfo bbGetInputType( const std::string &label ) const;
131     ///  Gets the output type of a given label
132     virtual TypeInfo bbGetOutputType( const std::string &label ) const;
133
134     ///  Gets the data of the input called <name>
135     virtual Data bbGetInput( const std::string &name )  = 0;
136     ///  Gets the data of the output called <name>
137     virtual Data bbGetOutput( const std::string &name ) = 0;
138
139     /// Sets the data of the input called <name>.
140     /// If setModified is false then does not call bbSetModifiedStatus()
141     virtual void bbSetInput( const std::string &name, Data data,
142                              bool setModified = true ) = 0;
143     virtual void bbBruteForceSetInputPointer( const std::string &name, 
144                                               void* data, 
145                                               bool setModified = true) =0;
146     ///  Sets the data of the output called <name>
147     virtual void bbSetOutput( const std::string &name, Data data) = 0;
148
149     /// Connects the input <name> to the connection c
150     virtual void bbConnectInput( const std::string& name, 
151                                  Connection::Pointer c);
152     /// Connects the output <name> to the connection c
153     virtual void bbConnectOutput( const std::string& name, 
154                                   Connection::Pointer c);
155     /// Disconnects the input <name> from the connection c
156     virtual void bbDisconnectInput( const std::string& name, 
157                                     Connection::Pointer c);
158     /// Disconnects the output <name> from the connection c
159     virtual void bbDisconnectOutput( const std::string& name, 
160                                      Connection::Pointer c);
161
162     ///  Returns the input connectors map
163     InputConnectorMapType&  bbGetInputConnectorMap() 
164     { return mInputConnectorMap; }
165     ///  Returns the output connectors map
166     OutputConnectorMapType& bbGetOutputConnectorMap() 
167     { return mOutputConnectorMap; }
168     ///  Returns the input connectors map (const)
169     const InputConnectorMapType&  bbGetInputConnectorMap() const 
170     { return mInputConnectorMap; } 
171     ///  Returns the output connectors map (const)
172     const OutputConnectorMapType& bbGetOutputConnectorMap() const 
173     { return mOutputConnectorMap; }      
174  
175
176     /// Prints the Help on the BlackBox type 
177     virtual void bbGetHelp(bool full=true) const;
178
179
180     //==================================================================
181     // Common inputs / outputs to all boxes
182     /// Returns the value of the input "BoxProcessMode"
183     std::string bbGetInputBoxProcessMode() { return bbmBoxProcessMode; }
184     /// Sets the value of the input "BoxProcessMode"
185     void bbSetInputBoxProcessMode(std::string a) { bbmBoxProcessMode = a; }
186     typedef enum
187       {
188         Pipeline,
189         Always,
190         Reactive
191       }
192       BoxProcessModeValue;
193     /// Returns the "decoded" value of the input "BoxProcessMode"
194     BoxProcessModeValue bbGetBoxProcessModeValue() const;
195   
196     virtual bool bbBoxProcessModeIsReactive() const;
197
198     virtual bool bbBoxProcessModeIsAlways() const;
199
200     /// Returns the value of the input "Execute" 
201     Void bbGetInputBoxExecute() { return Void(); }
202     /// Sets the value of the input "Execute"
203     void bbSetInputBoxExecute(Void = 0) {}
204
205     /// Returns the value of the output "Change"
206     Void bbGetOutputBoxChange() { return Void(); }
207     /// Sets the value of the output "Change" : signal a modification
208     void bbSetOutputBoxChange(Void = 0) { bbSetModifiedStatus(); }
209
210     //==================================================================    
211
212
213     //==================================================================    
214
215     /// Does nothing here : overloaded in ComplexBlackBox
216     void bbInsertHTMLGraph(  std::ofstream& s, 
217                              int detail, 
218                              int level,
219                              bool instanceOrtype,
220                              const std::string& output_dir,
221                              bool relative_link ) 
222     {}
223
224     /// Write Graphviz-dot description in file. 
225     /// Here dumps a single box description (i/o) but overloaded 
226     /// in ComplexBlackBox to dump the internal pipeline representation 
227     /// recursing into internal boxes descriptions if level>0.
228     /// detail = 1 : draw inputs and outputs (do not draw otherwise)
229     /// instanceOrtype = true : draw inputs and outputs VALUES 
230     ///  (uses bbGetInputAsString / bbGetOutputAsString which use adaptors)
231     /// If relative_link is true then creates relative hrefs
232     virtual void bbWriteDotFileBlackBox(FILE *ff,
233                                         BlackBox::Pointer parentblackbox, 
234                                         int detail, int level, 
235                                         bool instanceOrtype,
236                                         bool relative_link );
237     /// Auxiliary method for bbWriteDotFileBlackBox
238     virtual void bbWriteDotInputOutputName(FILE *ff,
239                                            bool inputoutput, 
240                                            int detail, int level);
241     
242      
243     virtual void bbShowRelations(BlackBox::Pointer parentblackbox, 
244                                  int detail, int level
245                                  );
246     
247     std::string bbGetOutputAsString( const std::string &output ); //,Factory *factory);
248     std::string bbGetInputAsString( const std::string &input); //,Factory *factory);
249     virtual BlackBox::Pointer bbFindBlackBox(const std::string &blackboxname) 
250     { return BlackBox::Pointer();}
251
252     virtual void Check(bool recursive = true);
253
254   protected:
255     //==================================================================
256     // PROTECTED PART : ACCESSIBLE TO THE BlackBox DEVELOPER 
257     // (IN INHERITED CLASSES)
258     /// Constructor that take the BlackBox's name
259     BlackBox(const std::string &name);
260     /// Constructor from an existing box (copy) with a new name 
261     BlackBox(BlackBox& from, const std::string &name);
262     //==================================================================
263
264
265     //==================================================================
266     ///  Sets the status of the box
267     void bbSetStatus( IOStatus t) { bbmStatus = t; } 
268     //==================================================================
269     
270
271  
272     /// @name Pipeline processing methods
273     ///  Methods which participate to (forward or backward) pipeline processing.
274     ///  Some are pure virtual and prepare particular update mechanism which are implemented by descendents (e.g. ForwardUpdate and UpdateChildren are made for WxContainerBlackBox particular update mechanism which must recurse a piece of the pipeline top-down).
275     /// The main method is bbBackwardUpdate which is called by bbExecute and implemented in UserBlackBox and ComplexBlackBox.
276     /// 
277     //@{
278
279     //==================================================================   
280     /// Recursive pipeline processing in backward direction 
281     /// (recursion is in backward direction however execution always goes forward).
282     /// Pure virtual; defined in UserBlackBox and ComplexBlackBox
283     /// 
284     /// \returns The final status of the box (UPTODATE or MODIFIED)
285     /// \param caller : The connection which invoked the method; null if called by bbExecute
286     ///
287     /// First checks that re-processing is needed (either Status==MODIFIED or InputProcessMode==Always)
288     /// then : 
289     /// - updates its inputs by calling bbUpdateInputs (which recursively calls bbBackwardUpdate on upstream boxes)
290     /// - calls bbCreateWidget
291     /// - calls bbProcess which is the user callback which does the actual processing
292     /// - calls bbUpdateChildren
293     /// - calls bbShowWidget which shows the widget associated to the box (if any)
294   public:
295     virtual IOStatus bbBackwardUpdate(Connection::Pointer caller) = 0;
296     //==================================================================
297
298     //==================================================================
299     /// Recursive pipeline processing in forward direction along "Child"-"Parent" connections
300     /// Pure virtual; defined in UserBlackBox and ComplexBlackBox
301     /// 
302     /// \param caller : The connection which invoked the method
303     ///
304     /// First checks that re-processing is needed (either Status==MODIFIED or InputProcessMode==Always)
305     /// then : 
306     /// - calls bbCreateWidget
307     /// - calls bbProcess which is the user callback which does the actual processing
308     /// - calls bbUpdateChildren which recursively calls bbForwardUpdate on connections attached the "Child" output
309     // virtual void bbForwardUpdate(Connection::Pointer caller) = 0;
310     //==================================================================
311   protected:
312     //==================================================================
313     /// Updates the BlackBox inputs and returns the final status of the inputs 
314     /// (==UPTODATE iff all inputs are UPTODATE)  
315     // If excludeParent == true then excludes the upstream box connected to input 'Parent' from recursive update
316     IOStatus bbUpdateInputs(bool excludeParent=false);
317     //==================================================================
318
319     //==================================================================
320     /// Updates the pipeline in upstream-downstream direction along the "Child"-"Parent" connections only.
321     /// Does nothing here. Overloaded in WxContainerBlackbox
322     //virtual void bbUpdateChildren( Connection::Pointer caller ) { }
323     //==================================================================
324
325     //==================================================================
326     /// Specific methods for window creation during pipeline execution
327     /// Creates the window associated to the box (called after bbUpdateInputs)
328     /// Does nothing here. Overloaded in WxBlackBox.
329     // virtual void bbCreateWindow() { }
330     /// Shows the window associated to the box 
331     /// (called after bbProcess during bbExecute)
332     /// Does nothing here but overloaded in WxBlackBox and WxContainerBlackBox
333     virtual void bbShowWindow(Connection::Pointer caller) { }
334  
335     virtual void bbHideWindow() {}
336    //==================================================================
337
338     //@}
339   public: 
340
341     static bool bbGlobalGetSomeBoxExecuting();
342     static void bbGlobalSetSomeBoxExecuting(bool b);
343
344     static void bbGlobalSetFreezeExecution(bool b);
345     static bool bbGlobalGetFreezeExecution();
346
347     /// Returns true if the box can "react",
348     /// which means execute in response to an input change 
349     virtual bool bbCanReact() const;
350     
351     
352     static void bbGlobalAddToExecutionList( BlackBox::Pointer b );
353     static void bbGlobalProcessExecutionList();
354
355     //==================================================================
356   protected:
357     //==================================================================
358     /// Allocates the i/o connectors of the black box
359     virtual void bbAllocateConnectors();
360     /// Desallocates the i/o connectors of the black box
361     virtual void bbDesallocateConnectors();
362     /// Copies the values of the inputs/output from the BlackBox from
363     virtual void bbCopyIOValues(BlackBox& from);
364     //==================================================================
365
366     bool bbGetExecuting() const { return bbmExecuting; }
367     void bbSetExecuting(bool b) { bbmExecuting = b; }
368
369     // Black box objects have a special deleter 
370     // which must take care of releasing the descriptor 
371     // **AFTER** the box is deleted 
372     // (Releasing it in the destructor may cause dl close and crash)
373     /// Black box deleter 
374     /// 1) Calls the user overloadable bbDelete method
375     /// 2) Releases the box descriptor
376     struct Deleter : public Object::Deleter
377     { 
378       Deleter();
379       void Delete(Object* p);
380     };
381
382     template <class U>
383     static boost::shared_ptr<U> MakeBlackBoxPointer(U* s, bool lock = false)
384     {
385       return MakePointer(s,BlackBox::Deleter(),lock);
386     }
387
388     virtual void bbDelete() { delete this; }
389   private:
390     
391  
392     //==================================================================
393     // PRIVATE PART 
394     /// The status of the box
395     IOStatus bbmStatus;
396     /// The name of the black-box
397     std::string bbmName;
398     /// The name of the package to which it belongs
399     std::string bbmPackageName;
400         
401     /// 0 : "Pipeline" mode : bbUpdate() only calls Process if Status == MODIFIED (normal pipeline processing)
402     /// 1 : "Always" mode : bbUpdate() always calls Process  
403     /// 2 : "Reactive" mode : bbSetModifiedStatus() calls bbUpdate()
404     std::string bbmBoxProcessMode;
405
406     /// The parent of the black box in the ComplexBlackBox hierarchy
407     BlackBox::WeakPointer bbmParent;
408     //==================================================================
409
410     //==================================================================
411     // Am I executing (to test pipeline cycles) ?
412     bool bbmExecuting;
413     //==================================================================
414
415    //==================================================================
416     // ATTRIBUTES
417     ///  Map that contains the output connectors of the black box
418     OutputConnectorMapType mOutputConnectorMap; 
419     ///  Map that contains the input connectors of the black box
420     InputConnectorMapType mInputConnectorMap;
421     //==================================================================
422
423
424  };
425   // Class BlackBox
426
427
428
429
430
431
432
433  
434 }
435 // namespace bbtk
436 #endif
437