]> Creatis software - bbtk.git/blob - kernel/src/bbtkBlackBox.h
*** empty log message ***
[bbtk.git] / kernel / src / bbtkBlackBox.h
1 /*=========================================================================                                                                               
2   Program:   bbtk
3   Module:    $RCSfile: bbtkBlackBox.h,v $
4   Language:  C++
5   Date:      $Date: 2008/12/11 09:50:35 $
6   Version:   $Revision: 1.21 $
7 =========================================================================*/
8
9 /* ---------------------------------------------------------------------
10
11 * Copyright (c) CREATIS-LRMN (Centre de Recherche en Imagerie Medicale)
12 * Authors : Eduardo Davila, Laurent Guigues, Jean-Pierre Roux
13 *
14 *  This software is governed by the CeCILL-B license under French law and 
15 *  abiding by the rules of distribution of free software. You can  use, 
16 *  modify and/ or redistribute the software under the terms of the CeCILL-B 
17 *  license as circulated by CEA, CNRS and INRIA at the following URL 
18 *  http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html 
19 *  or in the file LICENSE.txt.
20 *
21 *  As a counterpart to the access to the source code and  rights to copy,
22 *  modify and redistribute granted by the license, users are provided only
23 *  with a limited warranty  and the software's author,  the holder of the
24 *  economic rights,  and the successive licensors  have only  limited
25 *  liability. 
26 *
27 *  The fact that you are presently reading this means that you have had
28 *  knowledge of the CeCILL-B license and that you accept its terms.
29 * ------------------------------------------------------------------------ */                                                                         
30
31
32
33 /**
34  *  \file 
35  *  \brief Class bbtk::BlackBox : abstract black-box interface. 
36  */
37
38 /**
39  * \class bbtk::BlackBox
40  * \brief Abstract black-box interface 
41  */
42  
43 #ifndef __bbtkBlackBox_h__
44 #define __bbtkBlackBox_h__
45
46 #include "bbtkSystem.h"
47 #include "bbtkBlackBoxDescriptor.h"
48 #include "bbtkBlackBoxInputConnector.h"
49 //#include "bbtkBlackBoxOutputConnector.h"
50 #include <set>
51
52 // Signal/slot mechanism for output change events
53 #include <boost/signal.hpp>
54 #include <boost/bind.hpp>
55
56 namespace bbtk
57 {
58
59   
60   struct Void { Void(int = 0) {} };
61   
62   class Factory;
63   class Connection;
64   class BlackBoxOutputConnector;
65  
66
67
68   class BBTK_EXPORT BlackBox : public Object
69   {
70     BBTK_ABSTRACT_OBJECT_INTERFACE(BlackBox);
71   public: 
72     //==================================================================
73     // INTERFACE
74     //==================================================================
75     typedef boost::signals::trackable OutputChangeObserverType;
76     typedef boost::signal<void (bbtk::BlackBox::Pointer,
77                                 const std::string&,
78                                 IOStatus)>  OutputChangeSignalType;
79     typedef OutputChangeSignalType::slot_function_type 
80     OutputChangeCallbackType;
81  
82     /// The type of map of output connector pointers
83     typedef std::map<std::string, BlackBoxOutputConnector*> 
84     OutputConnectorMapType;
85     /// The type of map of input connector pointers
86     typedef std::map<std::string, BlackBoxInputConnector*> 
87     InputConnectorMapType;
88
89     /// Returns the pointer on the descriptor of the box
90     virtual BlackBoxDescriptor::Pointer bbGetDescriptor() const = 0;
91
92     /// Returns a pointer on a clone of the box with name <name>
93     virtual BlackBox::Pointer bbClone(const std::string& name) = 0;
94
95     /// User overloadable destruction method of a black box
96     virtual void bbUserDelete();
97
98     /// Returns the Name of the Type of the BlackBox
99     const std::string& bbGetTypeName() const 
100       { return bbGetDescriptor()->GetTypeName(); }
101  
102     
103     /// Returns the name of the BlackBox (instance)
104     const std::string& bbGetName() const { return bbmName; }
105
106     /// Returns the full name of the BlackBox (instance+type)
107     virtual std::string bbGetFullName() const;
108
109     /// Returns the name with the name of the parent prepended if any
110     virtual std::string bbGetNameWithParent() const;
111     
112     /// Returns the parent of the BlackBox, i.e the BlackBox that contains it (0 if none)
113     BlackBox::Pointer bbGetParent() const { return bbmParent.lock(); }
114
115
116     /// Main processing method of the box.
117     virtual void bbExecute(bool force = false);
118
119
120  
121   
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 update_time is false then does not update ChangeTime of input
141     virtual void bbSetInput( const std::string &name, Data data,
142                              bool update_time = true ) = 0;
143     virtual void bbBruteForceSetInputPointer( const std::string &name, 
144                                               void* data, 
145                                               bool update_time = true) =0;
146     ///  Sets the data of the output called <name>
147     virtual void bbSetOutput( const std::string &name, Data data) = 0;
148
149
150     /// Gets the status of the input called <name>
151     IOStatus bbGetInputStatus( const std::string &name ) const 
152     { return mInputConnectorMap.find(name)->second->GetStatus(); }
153
154     ///  Returns the input connectors map
155     InputConnectorMapType&  bbGetInputConnectorMap() 
156     { return mInputConnectorMap; }
157     ///  Returns the output connectors map
158     OutputConnectorMapType& bbGetOutputConnectorMap() 
159     { return mOutputConnectorMap; }
160     ///  Returns the input connectors map (const)
161     const InputConnectorMapType&  bbGetInputConnectorMap() const 
162     { return mInputConnectorMap; } 
163     ///  Returns the output connectors map (const)
164     const OutputConnectorMapType& bbGetOutputConnectorMap() const 
165     { return mOutputConnectorMap; }      
166
167     ///  Returns the input connector
168     BlackBoxInputConnector&  bbGetInputConnector(const std::string& n) 
169     { return *(mInputConnectorMap.find(n)->second); }
170     ///  Returns the output connector
171     BlackBoxOutputConnector& bbGetOutputConnector(const std::string& n) 
172     { return *(mOutputConnectorMap.find(n)->second); }
173     ///  Returns the input connector (const)
174     const BlackBoxInputConnector&  bbGetInputConnector(const std::string& n) const
175     { return *(mInputConnectorMap.find(n)->second); }
176     ///  Returns the output connector (const)
177     const BlackBoxOutputConnector& bbGetOutputConnector(const std::string& n) const 
178     { return *(mOutputConnectorMap.find(n)->second); }
179
180  
181     
182
183     /// Prints the Help on the BlackBox type 
184     virtual void bbGetHelp(bool full=true) const;
185
186     //==================================================================
187     /// Adds the function f to the list of functions to call when 
188     /// the output changes.
189     /// f is of type ChangeCallbackType which is basically:
190     /// void (*ChangeCallbackType)(bbtk::BlackBox::Pointer, 
191     ///                            const std::string&,
192     ///                            bbtk::IOStatus)
193     /// To pass a member function 'f' of an instance 'c' of a class 'C' 
194     /// as callback you have to 'bind' it, i.e. call:
195     /// bbAddOutputObserver ( "Out", boost::bind( &C::f , c, _1, _2, _3 ) );
196     /// The convenience macro BBTK_BIND_OUTPUT_OBSERVER ( c, C::f ) does it for you 
197     void bbAddOutputObserver(const std::string& output_name, 
198                              OutputChangeCallbackType f); 
199
200     /// Removes the function f from the list of functions to call when 
201     /// the output changes (TO WRITE)
202     void bbRemoveOutputObserver(const std::string& output_name, 
203                                 OutputChangeCallbackType f); 
204    //==================================================================
205     
206
207     //==================================================================
208     /// Signals that the BlackBox outputs have been modified 
209     /// (without marking the box as MODIFIED because its output state is ok : don't care if you understand : use it !).
210     /// This method should be used by widgets in response 
211     /// to user interaction when **ALL** outputs have been modified
212     /// (after the outputs has been updated !).
213     /// DO NOT PASS reaction = false OR WILL NOT WORK PROPERLY
214     /// ** USER INTENDED **
215     virtual void bbSignalOutputModification(bool reaction = true);
216     /// Signals that the BlackBox output "output_name" has been modified 
217     /// (without marking the box as MODIFIED because its output state is ok : don't care if you understand : use it !). 
218     /// This method should be used by widgets in response to user interaction 
219     /// only when **ONE** output has been modified
220     /// (after the output has been updated !)
221     /// DO NOT PASS reaction = false OR WILL NOT WORK PROPERLY
222     /// ** USER INTENDED **
223     virtual void bbSignalOutputModification( const std::string& output_name,
224                                              bool reaction = true);
225     /// Signals that the BlackBox vector of outputs "output_name" 
226     /// have been modified.
227     /// Should be used when more than ONE output is modified but not ALL 
228     /// (optimization issue).
229     /// (without marking the box as MODIFIED because its output state is ok). 
230     /// This method should be used by widgets in response to user interaction 
231     /// When more than one output has been changed but not all
232     /// (after the outputs have been updated of course!)
233     /// DO NOT PASS reaction = false OR WILL NOT WORK PROPERLY
234     /// ** USER INTENDED **
235     virtual void bbSignalOutputModification( const std::vector<std::string>& 
236                                              output_name,
237                                              bool reaction = true);
238    //==================================================================
239
240
241
242    //==================================================================
243     // Common inputs / outputs to all boxes
244     /// Returns the value of the input "BoxProcessMode"
245     std::string bbGetInputBoxProcessMode() { return bbmBoxProcessMode; }
246     /// Sets the value of the input "BoxProcessMode"
247     void bbSetInputBoxProcessMode(std::string a) { bbmBoxProcessMode = a; }
248     typedef enum
249       {
250         Pipeline,
251         Always,
252         Reactive
253       }
254       BoxProcessModeValue;
255     /// Returns the "decoded" value of the input "BoxProcessMode"
256     BoxProcessModeValue bbGetBoxProcessModeValue() const;
257   
258     virtual bool bbBoxProcessModeIsReactive() const;
259
260     virtual bool bbBoxProcessModeIsAlways() const;
261
262     /// Returns the value of the input "Execute" 
263     Void bbGetInputBoxExecute() { return Void(); }
264     /// Sets the value of the input "Execute"
265     void bbSetInputBoxExecute(Void = 0) {}
266
267     /// Returns the value of the output "Change"
268     Void bbGetOutputBoxChange() { return Void(); }
269     /// Sets the value of the output "Change" : signal a modification
270     void bbSetOutputBoxChange(Void = 0) { } //bbSetModifiedStatus(); }
271
272     //==================================================================    
273
274
275     //==================================================================    
276
277     /// Does nothing here : overloaded in ComplexBlackBox
278     void bbInsertHTMLGraph(  std::ofstream& s, 
279                              int detail, 
280                              int level,
281                              bool instanceOrtype,
282                              const std::string& output_dir,
283                              bool relative_link ) 
284     {}
285
286     /// Write Graphviz-dot description in file. 
287     /// Here dumps a single box description (i/o) but overloaded 
288     /// in ComplexBlackBox to dump the internal pipeline representation 
289     /// recursing into internal boxes descriptions if level>0.
290     /// detail = 1 : draw inputs and outputs (do not draw otherwise)
291     /// instanceOrtype = true : draw inputs and outputs VALUES 
292     ///  (uses bbGetInputAsString / bbGetOutputAsString which use adaptors)
293     /// If relative_link is true then creates relative hrefs
294     virtual void bbWriteDotFileBlackBox(FILE *ff,
295                                         BlackBox::Pointer parentblackbox, 
296                                         int detail, int level, 
297                                         bool instanceOrtype,
298                                         bool relative_link );
299     /// Auxiliary method for bbWriteDotFileBlackBox
300     virtual void bbWriteDotInputOutputName(FILE *ff,
301                                            bool inputoutput, 
302                                            int detail, int level);
303     
304      
305     virtual void bbShowRelations(BlackBox::Pointer parentblackbox, 
306                                  int detail, int level
307                                  );
308     
309     std::string bbGetOutputAsString( const std::string &output ); //,Factory *factory);
310     std::string bbGetInputAsString( const std::string &input); //,Factory *factory);
311     virtual BlackBox::Pointer bbFindBlackBox(const std::string &blackboxname) 
312     { return BlackBox::Pointer();}
313
314     virtual void Check(bool recursive = true);
315
316         virtual void bbUserOnShow() { }
317         void bbUserOnShowWidget(std::string nameInput);
318
319   protected:
320     //==================================================================
321     // PROTECTED PART : ACCESSIBLE TO THE BlackBox DEVELOPER 
322     // (IN INHERITED CLASSES)
323     /// Constructor that take the BlackBox's name
324     BlackBox(const std::string &name);
325     /// Constructor from an existing box (copy) with a new name 
326     BlackBox(BlackBox& from, const std::string &name);
327     //==================================================================
328
329
330     //==================================================================
331     /// Signals that the input whose connector is c has changed 
332     /// and propagates the info downward
333     /// ** NOT USER INTENDED **
334     virtual void bbSetStatusAndPropagate(BlackBoxInputConnector* c,
335                                          IOStatus s);
336     //==================================================================
337     
338   private:
339     //==================================================================
340     friend class Connection;
341     friend class ComplexBlackBox;
342
343     /// Sets the parent of the BlackBox
344     void bbSetParent(BlackBox::Pointer p) { bbmParent = p; }
345     
346
347     /// Connects the input <name> to the connection c
348     virtual void bbConnectInput( const std::string& name, 
349                                  Connection* c);
350     /// Connects the output <name> to the connection c
351     virtual void bbConnectOutput( const std::string& name, 
352                                   Connection* c);
353     /// Disconnects the input <name> from the connection c
354     virtual void bbDisconnectInput( const std::string& name, 
355                                     Connection* c);
356     /// Disconnects the output <name> from the connection c
357     virtual void bbDisconnectOutput( const std::string& name, 
358                                      Connection* c);
359
360     //==================================================================
361   protected: 
362     /// @name Pipeline processing methods
363     ///  Methods which participate to pipeline processing.
364     //@{
365
366     
367     //==================================================================   
368     /// Recursive execution method
369     /// 
370     /// \param caller : The connection which invoked the method; null if called by bbExecute
371     virtual void bbRecursiveExecute(Connection::Pointer caller);
372     //==================================================================
373     
374     //==================================================================
375     /// Updates the BlackBox inputs
376     /// Calls RecursiveExecute on all BlackBoxInputConnector
377     /// \returns The maximum of final IOStatus after each input update
378     IOStatus bbUpdateInputs();
379     //==================================================================
380
381    //==================================================================
382     /// Actual processing method (vitual)
383     /// Overloaded in AtomicBlacBox and descendants 
384     virtual void bbProcess() 
385     {
386       bbtkError("BlackBox::bbProcess called : how can this happen ?");
387 //      this->bbUserProcess(); 
388     }
389     //==================================================================
390
391     //==================================================================
392     /// Computes the final IOStatus of inputs and outputs after processing
393     void bbComputePostProcessStatus();
394     //==================================================================
395
396  
397     //==================================================================
398     /// Specific methods for window creation during pipeline execution
399     /// Creates the window associated to the box (called after bbUpdateInputs)
400     /// Does nothing here. Overloaded in WxBlackBox.
401     // virtual void bbCreateWindow() { }
402     /// Shows the window associated to the box 
403     /// (called after bbProcess during bbExecute)
404     /// Does nothing here but overloaded in WxBlackBox and WxContainerBlackBox
405     //    virtual void bbShowWindow(Connection::Pointer caller) { }
406     //    virtual void bbHideWindow() {}
407     //    virtual void bbCloseWindow() { }
408     //==================================================================
409
410     //@}
411   public: 
412
413     static bool bbGlobalGetSomeBoxExecuting();
414     static void bbGlobalSetSomeBoxExecuting(bool b);
415
416     static void bbGlobalSetFreezeExecution(bool b);
417     static bool bbGlobalGetFreezeExecution();
418
419     /// Returns true if the box can "react",
420     /// which means execute in response to an input change 
421     virtual bool bbCanReact() const;
422     
423     /// Returns true iff the box is executing
424     bool bbGetExecuting() const { return bbmExecuting; }
425
426   protected:  
427     static void bbGlobalAddToExecutionList( BlackBox::Pointer b );
428     static void bbGlobalProcessExecutionList();
429     /// Sets the bbmExecuting bool returned by bbGetExecuting
430     void bbSetExecuting(bool b) { bbmExecuting = b; }
431
432     //==================================================================
433   protected:
434     //==================================================================
435     /// Allocates the i/o connectors of the black box
436     virtual void bbAllocateConnectors();
437     /// Desallocates the i/o connectors of the black box
438     virtual void bbDesallocateConnectors();
439     /// Copies the values of the inputs/output from the BlackBox from
440     virtual void bbCopyIOValues(BlackBox& from);
441     //==================================================================
442
443     //==================================================================
444     // Black box objects have a special deleter 
445     // which must take care of releasing the descriptor 
446     // **AFTER** the box is deleted 
447     // (Releasing it in the destructor may cause dl close and crash)
448     /// Black box deleter 
449     /// 1) Calls the user overloadable bbDelete method
450     /// 2) Releases the box descriptor
451     struct BBTK_EXPORT Deleter : public Object::Deleter
452     { 
453       Deleter();
454       void Delete(Object* p);
455     };
456     //==================================================================
457
458     //==================================================================
459     template <class U>
460     static boost::shared_ptr<U> MakeBlackBoxPointer(U* s, bool lock = false)
461     {
462       return MakePointer(s,BlackBox::Deleter(),lock);
463     }
464     //==================================================================
465
466     //==================================================================
467     virtual void bbDelete() { delete this; }
468     //==================================================================
469
470
471     //==================================================================
472   private:
473     //==================================================================
474  
475     //==================================================================
476     // ATTRIBUTES
477     /// Is the box executing ?
478     bool bbmExecuting;
479     /// The name of the black-box
480     std::string bbmName;
481     /// The name of the package to which it belongs
482     std::string bbmPackageName;
483     /// The box processing mode
484     /// 0 : "Pipeline" mode 
485     /// 1 : "Always" mode 
486     /// 2 : "Reactive" mode 
487     std::string bbmBoxProcessMode;
488     /// The parent of the black box in the ComplexBlackBox hierarchy
489     BlackBox::WeakPointer bbmParent;
490     //==================================================================
491
492
493    //==================================================================
494     // ATTRIBUTES
495     ///  Map that contains the output connectors of the black box
496     OutputConnectorMapType mOutputConnectorMap; 
497     ///  Map that contains the input connectors of the black box
498     InputConnectorMapType mInputConnectorMap;
499     //==================================================================
500
501
502  };
503   // Class BlackBox
504
505
506
507   /// Convenient macro to create output observer callbacks (freehand functions) from object and method pointer (see samples/SampleOutputObserver)
508 #define BBTK_MAKE_OUTPUT_OBSERVER(OBJECT,METHOD) \
509     boost::bind( METHOD, OBJECT, _1, _2, _3)
510
511
512
513
514  
515 }
516 // namespace bbtk
517 #endif
518