]> Creatis software - bbtk.git/blob - kernel/src/bbtkBlackBox.h
*** empty log message ***
[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/22 14:30:25 $
7   Version:   $Revision: 1.8 $
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   class Connection;
47
48   class BBTK_EXPORT BlackBox : public Object
49   {
50     BBTK_ABSTRACT_OBJECT_INTERFACE(BlackBox);
51   public: 
52     //==================================================================
53     // INTERFACE
54     //==================================================================
55  
56     /// The type of map of output connector pointers
57     typedef std::map<std::string, BlackBoxOutputConnector*> 
58     OutputConnectorMapType;
59     /// The type of map of input connector pointers
60     typedef std::map<std::string, BlackBoxInputConnector*> 
61     InputConnectorMapType;
62
63     /// Returns the pointer on the descriptor of the box
64     virtual BlackBoxDescriptor::Pointer bbGetDescriptor() const = 0;
65
66     /// Returns a pointer on a clone of the box with name <name>
67     virtual BlackBox::Pointer bbClone(const std::string& name) = 0;
68
69     /// User overloadable destruction method of a black box
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     /// Returns the parent of the BlackBox, i.e the BlackBox that contains it (0 if none)
87     BlackBox::Pointer bbGetParent() const { return bbmParent.lock(); }
88
89
90     /// Main processing method of the box.
91     virtual void bbExecute(bool force = false);
92
93     ///  Signals that the BlackBox has been modified through the input connector c
94     /// and propagates it downward
95     virtual void bbSetModifiedStatus(BlackBoxInputConnector* c = 0);
96     /// Signals that the BlackBox outputs have been modified 
97     /// without marking the box as MODIFIED because its output state is ok. 
98     /// This method should be used by widgets in response 
99     /// to user interaction when **ALL** outputs have been modified
100     /// (after the outputs has been updated !)
101     virtual void bbSignalOutputModification(bool reaction = true);
102     ///  Signals that the BlackBox output "output_name" have been modified 
103     /// without marking the box as MODIFIED because its output state is ok. 
104     /// This method should be used by widgets in response to user interaction 
105     /// only when **ONE** output has been modified
106     /// (after the output has been updated !)
107     virtual void bbSignalOutputModification( const std::string& output_name,
108 bool reaction = true);
109     ///  Signals that the BlackBox vector of outputs "output_name" 
110     ///  have been modified 
111     /// without marking the box as MODIFIED because its output state is ok. 
112     /// This method should be used by widgets in response to user interaction 
113     /// When more than one output has been changed but not all
114     /// (after the outputs have been updated of course!)
115     virtual void bbSignalOutputModification( const std::vector<std::string>& output_name,
116 bool reaction = true);
117
118     /// Gets the status of the box
119     virtual const IOStatus& bbGetStatus() const { return bbmStatus; }
120
121
122     /// Returns true iff the BlackBox has an input of name label
123     virtual bool bbHasInput(const std::string& label) const;
124     /// Returns true iff the BlackBox has an output of name label
125     virtual bool bbHasOutput(const std::string& label) const;
126
127     ///  Gets the input type of a given label
128     virtual TypeInfo bbGetInputType( const std::string &label ) const;
129     ///  Gets the output type of a given label
130     virtual TypeInfo bbGetOutputType( const std::string &label ) const;
131
132     ///  Gets the data of the input called <name>
133     virtual Data bbGetInput( const std::string &name )  = 0;
134     ///  Gets the data of the output called <name>
135     virtual Data bbGetOutput( const std::string &name ) = 0;
136
137     /// Sets the data of the input called <name>.
138     /// If setModified is false then does not call bbSetModifiedStatus()
139     virtual void bbSetInput( const std::string &name, Data data,
140                              bool setModified = true ) = 0;
141     virtual void bbBruteForceSetInputPointer( const std::string &name, 
142                                               void* data, 
143                                               bool setModified = true) =0;
144     ///  Sets the data of the output called <name>
145     virtual void bbSetOutput( const std::string &name, Data data) = 0;
146
147
148     ///  Returns the input connectors map
149     InputConnectorMapType&  bbGetInputConnectorMap() 
150     { return mInputConnectorMap; }
151     ///  Returns the output connectors map
152     OutputConnectorMapType& bbGetOutputConnectorMap() 
153     { return mOutputConnectorMap; }
154     ///  Returns the input connectors map (const)
155     const InputConnectorMapType&  bbGetInputConnectorMap() const 
156     { return mInputConnectorMap; } 
157     ///  Returns the output connectors map (const)
158     const OutputConnectorMapType& bbGetOutputConnectorMap() const 
159     { return mOutputConnectorMap; }      
160  
161
162     /// Prints the Help on the BlackBox type 
163     virtual void bbGetHelp(bool full=true) const;
164
165
166     //==================================================================
167     // Common inputs / outputs to all boxes
168     /// Returns the value of the input "BoxProcessMode"
169     std::string bbGetInputBoxProcessMode() { return bbmBoxProcessMode; }
170     /// Sets the value of the input "BoxProcessMode"
171     void bbSetInputBoxProcessMode(std::string a) { bbmBoxProcessMode = a; }
172     typedef enum
173       {
174         Pipeline,
175         Always,
176         Reactive
177       }
178       BoxProcessModeValue;
179     /// Returns the "decoded" value of the input "BoxProcessMode"
180     BoxProcessModeValue bbGetBoxProcessModeValue() const;
181   
182     virtual bool bbBoxProcessModeIsReactive() const;
183
184     virtual bool bbBoxProcessModeIsAlways() const;
185
186     /// Returns the value of the input "Execute" 
187     Void bbGetInputBoxExecute() { return Void(); }
188     /// Sets the value of the input "Execute"
189     void bbSetInputBoxExecute(Void = 0) {}
190
191     /// Returns the value of the output "Change"
192     Void bbGetOutputBoxChange() { return Void(); }
193     /// Sets the value of the output "Change" : signal a modification
194     void bbSetOutputBoxChange(Void = 0) { bbSetModifiedStatus(); }
195
196     //==================================================================    
197
198
199     //==================================================================    
200
201     /// Does nothing here : overloaded in ComplexBlackBox
202     void bbInsertHTMLGraph(  std::ofstream& s, 
203                              int detail, 
204                              int level,
205                              bool instanceOrtype,
206                              const std::string& output_dir,
207                              bool relative_link ) 
208     {}
209
210     /// Write Graphviz-dot description in file. 
211     /// Here dumps a single box description (i/o) but overloaded 
212     /// in ComplexBlackBox to dump the internal pipeline representation 
213     /// recursing into internal boxes descriptions if level>0.
214     /// detail = 1 : draw inputs and outputs (do not draw otherwise)
215     /// instanceOrtype = true : draw inputs and outputs VALUES 
216     ///  (uses bbGetInputAsString / bbGetOutputAsString which use adaptors)
217     /// If relative_link is true then creates relative hrefs
218     virtual void bbWriteDotFileBlackBox(FILE *ff,
219                                         BlackBox::Pointer parentblackbox, 
220                                         int detail, int level, 
221                                         bool instanceOrtype,
222                                         bool relative_link );
223     /// Auxiliary method for bbWriteDotFileBlackBox
224     virtual void bbWriteDotInputOutputName(FILE *ff,
225                                            bool inputoutput, 
226                                            int detail, int level);
227     
228      
229     virtual void bbShowRelations(BlackBox::Pointer parentblackbox, 
230                                  int detail, int level
231                                  );
232     
233     std::string bbGetOutputAsString( const std::string &output ); //,Factory *factory);
234     std::string bbGetInputAsString( const std::string &input); //,Factory *factory);
235     virtual BlackBox::Pointer bbFindBlackBox(const std::string &blackboxname) 
236     { return BlackBox::Pointer();}
237
238     virtual void Check(bool recursive = true);
239
240   protected:
241     //==================================================================
242     // PROTECTED PART : ACCESSIBLE TO THE BlackBox DEVELOPER 
243     // (IN INHERITED CLASSES)
244     /// Constructor that take the BlackBox's name
245     BlackBox(const std::string &name);
246     /// Constructor from an existing box (copy) with a new name 
247     BlackBox(BlackBox& from, const std::string &name);
248     //==================================================================
249
250
251     //==================================================================
252     ///  Sets the status of the box
253     void bbSetStatus( IOStatus t) { bbmStatus = t; } 
254     //==================================================================
255     
256   private:
257     friend class Connection;
258     friend class ComplexBlackBox;
259
260     /// Sets the parent of the BlackBox
261     void bbSetParent(BlackBox::Pointer p) { bbmParent = p; }
262     
263
264     /// Connects the input <name> to the connection c
265     virtual void bbConnectInput( const std::string& name, 
266                                  Connection* c);
267     /// Connects the output <name> to the connection c
268     virtual void bbConnectOutput( const std::string& name, 
269                                   Connection* c);
270     /// Disconnects the input <name> from the connection c
271     virtual void bbDisconnectInput( const std::string& name, 
272                                     Connection* c);
273     /// Disconnects the output <name> from the connection c
274     virtual void bbDisconnectOutput( const std::string& name, 
275                                      Connection* c);
276
277
278  
279     /// @name Pipeline processing methods
280     ///  Methods which participate to (forward or backward) pipeline processing.
281     ///  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).
282     /// The main method is bbBackwardUpdate which is called by bbExecute and implemented in UserBlackBox and ComplexBlackBox.
283     /// 
284     //@{
285
286     //==================================================================   
287     /// Recursive pipeline processing in backward direction 
288     /// (recursion is in backward direction however execution always goes forward).
289     /// Pure virtual; defined in UserBlackBox and ComplexBlackBox
290     /// 
291     /// \returns The final status of the box (UPTODATE or MODIFIED)
292     /// \param caller : The connection which invoked the method; null if called by bbExecute
293     ///
294     /// First checks that re-processing is needed (either Status==MODIFIED or InputProcessMode==Always)
295     /// then : 
296     /// - updates its inputs by calling bbUpdateInputs (which recursively calls bbBackwardUpdate on upstream boxes)
297     /// - calls bbCreateWidget
298     /// - calls bbProcess which is the user callback which does the actual processing
299     /// - calls bbUpdateChildren
300     /// - calls bbShowWidget which shows the widget associated to the box (if any)
301   protected:
302     virtual IOStatus bbBackwardUpdate(Connection::Pointer caller) = 0;
303     //==================================================================
304
305     //==================================================================
306     /// Recursive pipeline processing in forward direction along "Child"-"Parent" connections
307     /// Pure virtual; defined in UserBlackBox and ComplexBlackBox
308     /// 
309     /// \param caller : The connection which invoked the method
310     ///
311     /// First checks that re-processing is needed (either Status==MODIFIED or InputProcessMode==Always)
312     /// then : 
313     /// - calls bbCreateWidget
314     /// - calls bbProcess which is the user callback which does the actual processing
315     /// - calls bbUpdateChildren which recursively calls bbForwardUpdate on connections attached the "Child" output
316     // virtual void bbForwardUpdate(Connection::Pointer caller) = 0;
317     //==================================================================
318   protected:
319     //==================================================================
320     /// Updates the BlackBox inputs and returns the final status of the inputs 
321     /// (==UPTODATE iff all inputs are UPTODATE)  
322     // If excludeParent == true then excludes the upstream box connected to input 'Parent' from recursive update
323     IOStatus bbUpdateInputs(bool excludeParent=false);
324     //==================================================================
325
326     //==================================================================
327     /// Updates the pipeline in upstream-downstream direction along the "Child"-"Parent" connections only.
328     /// Does nothing here. Overloaded in WxContainerBlackbox
329     //virtual void bbUpdateChildren( Connection::Pointer caller ) { }
330     //==================================================================
331
332     //==================================================================
333     /// Specific methods for window creation during pipeline execution
334     /// Creates the window associated to the box (called after bbUpdateInputs)
335     /// Does nothing here. Overloaded in WxBlackBox.
336     // virtual void bbCreateWindow() { }
337     /// Shows the window associated to the box 
338     /// (called after bbProcess during bbExecute)
339     /// Does nothing here but overloaded in WxBlackBox and WxContainerBlackBox
340     virtual void bbShowWindow(Connection::Pointer caller) { }
341  
342     virtual void bbHideWindow() {}
343    //==================================================================
344
345     //@}
346   public: 
347
348     static bool bbGlobalGetSomeBoxExecuting();
349     static void bbGlobalSetSomeBoxExecuting(bool b);
350
351     static void bbGlobalSetFreezeExecution(bool b);
352     static bool bbGlobalGetFreezeExecution();
353
354     /// Returns true if the box can "react",
355     /// which means execute in response to an input change 
356     virtual bool bbCanReact() const;
357     
358   protected:  
359     static void bbGlobalAddToExecutionList( BlackBox::Pointer b );
360     static void bbGlobalProcessExecutionList();
361
362     //==================================================================
363   protected:
364     //==================================================================
365     /// Allocates the i/o connectors of the black box
366     virtual void bbAllocateConnectors();
367     /// Desallocates the i/o connectors of the black box
368     virtual void bbDesallocateConnectors();
369     /// Copies the values of the inputs/output from the BlackBox from
370     virtual void bbCopyIOValues(BlackBox& from);
371     //==================================================================
372
373     // Black box objects have a special deleter 
374     // which must take care of releasing the descriptor 
375     // **AFTER** the box is deleted 
376     // (Releasing it in the destructor may cause dl close and crash)
377     /// Black box deleter 
378     /// 1) Calls the user overloadable bbDelete method
379     /// 2) Releases the box descriptor
380     struct Deleter : public Object::Deleter
381     { 
382       Deleter();
383       void Delete(Object* p);
384     };
385
386     template <class U>
387     static boost::shared_ptr<U> MakeBlackBoxPointer(U* s, bool lock = false)
388     {
389       return MakePointer(s,BlackBox::Deleter(),lock);
390     }
391
392     virtual void bbDelete() { delete this; }
393   private:
394     
395  
396     //==================================================================
397     // PRIVATE PART 
398     /// The status of the box
399     IOStatus bbmStatus;
400     /// The name of the black-box
401     std::string bbmName;
402     /// The name of the package to which it belongs
403     std::string bbmPackageName;
404         
405     /// 0 : "Pipeline" mode : bbUpdate() only calls Process if Status == MODIFIED (normal pipeline processing)
406     /// 1 : "Always" mode : bbUpdate() always calls Process  
407     /// 2 : "Reactive" mode : bbSetModifiedStatus() calls bbUpdate()
408     std::string bbmBoxProcessMode;
409
410     /// The parent of the black box in the ComplexBlackBox hierarchy
411     BlackBox::WeakPointer bbmParent;
412     //==================================================================
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