1 /*=========================================================================
3 Module: $RCSfile: bbtkBlackBox.h,v $
5 Date: $Date: 2009/10/05 22:44:48 $
6 Version: $Revision: 1.29 $
7 =========================================================================*/
9 /* ---------------------------------------------------------------------
11 * Copyright (c) CREATIS-LRMN (Centre de Recherche en Imagerie Medicale)
12 * Authors : Eduardo Davila, Laurent Guigues, Jean-Pierre Roux
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.
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
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 * ------------------------------------------------------------------------ */
35 * \brief Class bbtk::BlackBox : abstract black-box interface.
39 * \class bbtk::BlackBox
40 * \brief Abstract black-box interface
43 #ifndef __bbtkBlackBox_h__
44 #define __bbtkBlackBox_h__
46 #include "bbtkSystem.h"
47 #include "bbtkMessageManager.h"
48 #include "bbtkBlackBoxDescriptor.h"
49 #include "bbtkBlackBoxInputConnector.h"
50 //#include "bbtkBlackBoxOutputConnector.h"
53 // Signal/slot mechanism for output change events
54 #include <boost/signal.hpp>
55 #include <boost/bind.hpp>
58 #define bbtkBlackBoxMessage(key,level,mess) \
59 bbtkMessage(key,level,"["<<bbGetName()<<"] "<<mess)
60 #define bbtkBlackBoxDebugMessage(key,level,mess) \
61 bbtkDebugMessage(key,level,"["<<bbGetName()<<"] "<<mess)
67 struct Void { Void(int = 0) {} };
71 class BlackBoxOutputConnector;
75 class BBTK_EXPORT BlackBox : public Object
77 BBTK_ABSTRACT_OBJECT_INTERFACE(BlackBox);
82 //==================================================================
84 //==================================================================
85 typedef boost::signals::trackable OutputChangeObserverType;
86 typedef boost::signal<void (bbtk::BlackBox::Pointer,
88 IOStatus)> OutputChangeSignalType;
89 typedef OutputChangeSignalType::slot_function_type
90 OutputChangeCallbackType;
92 /// The type of map of output connector pointers
93 typedef std::map<std::string, BlackBoxOutputConnector*>
94 OutputConnectorMapType;
95 /// The type of map of input connector pointers
96 typedef std::map<std::string, BlackBoxInputConnector*>
97 InputConnectorMapType;
98 //==================================================================
101 //==================================================================
102 /// @name Pipeline processing methods
103 /// Methods which participate to pipeline processing.
105 /// Main processing method of the box.
106 virtual void bbExecute(bool force = false);
108 //==================================================================
114 //==================================================================
115 /// Returns a pointer on a clone of the box with name <name>
116 virtual BlackBox::Pointer bbClone(const std::string& name) = 0;
117 //==================================================================
120 //==================================================================
121 /// @name General accessors
122 /// Methods which give access to general informations on the box
125 /// Returns the pointer on the descriptor of the box
126 virtual BlackBoxDescriptor::Pointer bbGetDescriptor() const = 0;
128 /// Returns the Name of the Type of the BlackBox
129 const std::string& bbGetTypeName() const
130 { return bbGetDescriptor()->GetTypeName(); }
133 /// Returns the name of the BlackBox (instance)
134 const std::string& bbGetName() const { return bbmName; }
136 /// Returns the full name of the BlackBox (instance+type)
137 virtual std::string bbGetFullName() const;
139 /// Returns the name with the name of the parent prepended if any
140 virtual std::string bbGetNameWithParent() const;
142 /// Returns the parent of the BlackBox, i.e the BlackBox that contains it (0 if none)
143 BlackBox::Pointer bbGetParent() const { return bbmParent.lock(); }
146 //==================================================================
150 //==================================================================
151 /// @name Inputs/Outputs related methods
152 /// Methods related to the box inputs and outputs
155 /// Returns true iff the BlackBox has an input of name label
156 virtual bool bbHasInput(const std::string& label) const;
157 /// Gets the input type of a given label
158 virtual TypeInfo bbGetInputType( const std::string &label ) const;
159 /// Gets the status of the input called <name>
160 IOStatus bbGetInputStatus( const std::string &name ) const
161 { return mInputConnectorMap.find(name)->second->GetStatus(); }
162 /// Gets the data of the input called <name>
163 virtual Data bbGetInput( const std::string &name ) = 0;
164 /// Gets the data of the input called <name> as a string using an Adaptor if possible (else returns empty string)
165 std::string bbGetInputAsString( const std::string &input);
168 /// Sets the data of the input called <name>.
169 /// If update_time is false then does not update ChangeTime of input
170 virtual void bbSetInput( const std::string &name, Data data,
171 bool update_time = true ) = 0;
172 /// [SYSTEM]: Sets the data of the input called <name> which **MUST* be a pointer
173 virtual void bbBruteForceSetInputPointer( const std::string &name,
175 bool update_time = true) =0;
178 /// Returns true iff the BlackBox has an output of name label
179 virtual bool bbHasOutput(const std::string& label) const;
180 /// Gets the output type of a given label
181 virtual TypeInfo bbGetOutputType( const std::string &label ) const;
182 /// Gets the data of the output called <name>
183 virtual Data bbGetOutput( const std::string &name ) = 0;
184 /// Gets the data of the output called <name> as a string using an Adaptor if possible (else returns empty string)
185 std::string bbGetOutputAsString( const std::string &output ); //,Factory *factory);
187 /// Sets the data of the output called <name>
188 virtual void bbSetOutput( const std::string &name, Data data) = 0;
191 /// Returns the input connectors map
192 InputConnectorMapType& bbGetInputConnectorMap()
193 { return mInputConnectorMap; }
194 /// Returns the input connectors map (const)
195 const InputConnectorMapType& bbGetInputConnectorMap() const
196 { return mInputConnectorMap; }
197 /// Returns the input connector
198 BlackBoxInputConnector& bbGetInputConnector(const std::string& n)
199 { return *(mInputConnectorMap.find(n)->second); }
200 /// Returns the input connector (const)
201 const BlackBoxInputConnector& bbGetInputConnector(const std::string& n) const
202 { return *(mInputConnectorMap.find(n)->second); }
205 /// Returns the output connectors map
206 OutputConnectorMapType& bbGetOutputConnectorMap()
207 { return mOutputConnectorMap; }
208 /// Returns the output connectors map (const)
209 const OutputConnectorMapType& bbGetOutputConnectorMap() const
210 { return mOutputConnectorMap; }
211 /// Returns the output connector
212 BlackBoxOutputConnector& bbGetOutputConnector(const std::string& n)
213 { return *(mOutputConnectorMap.find(n)->second); }
214 /// Returns the output connector (const)
215 const BlackBoxOutputConnector& bbGetOutputConnector(const std::string& n) const
216 { return *(mOutputConnectorMap.find(n)->second); }
219 //==================================================================
221 /// Prints the Help on the BlackBox type
222 virtual void bbGetHelp(bool full=true) const;
226 //==================================================================
227 /// @name Output signals / observers related methods
228 /// Methods related to signals emitted by outputs and the
231 //==================================================================
232 /// Adds the function f to the list of functions to call when
233 /// the output changes.
234 /// f is of type ChangeCallbackType which is basically:
235 /// void (*ChangeCallbackType)(bbtk::BlackBox::Pointer,
236 /// const std::string&,
238 /// To pass a member function 'f' of an instance 'c' of a class 'C'
239 /// as callback you have to 'bind' it, i.e. call:
240 /// bbAddOutputObserver ( "Out", boost::bind( &C::f , c, _1, _2, _3 ) );
241 /// The convenience macro BBTK_BIND_OUTPUT_OBSERVER ( c, C::f ) does it for you
242 void bbAddOutputObserver(const std::string& output_name,
243 OutputChangeCallbackType f);
245 /// Removes the function f from the list of functions to call when
246 /// the output changes (TO WRITE)
247 void bbRemoveOutputObserver(const std::string& output_name,
248 OutputChangeCallbackType f);
249 //==================================================================
252 //==================================================================
253 /// Signals that the BlackBox outputs have been modified
254 /// (without marking the box as MODIFIED because its output state is ok : don't care if you understand : use it !).
255 /// This method should be used by widgets in response
256 /// to user interaction when **ALL** outputs have been modified
257 /// (after the outputs has been updated !).
258 /// DO NOT PASS reaction = false OR WILL NOT WORK PROPERLY
259 /// ** USER INTENDED **
260 virtual void bbSignalOutputModification(bool reaction = true);
261 /// Signals that the BlackBox output "output_name" has been modified
262 /// (without marking the box as MODIFIED because its output state is ok : don't care if you understand : use it !).
263 /// This method should be used by widgets in response to user interaction
264 /// only when **ONE** output has been modified
265 /// (after the output has been updated !)
266 /// DO NOT PASS reaction = false OR WILL NOT WORK PROPERLY
267 /// ** USER INTENDED **
268 virtual void bbSignalOutputModification( const std::string& output_name,
269 bool reaction = true);
270 /// Signals that the BlackBox vector of outputs "output_name"
271 /// have been modified.
272 /// Should be used when more than ONE output is modified but not ALL
273 /// (optimization issue).
274 /// (without marking the box as MODIFIED because its output state is ok).
275 /// This method should be used by widgets in response to user interaction
276 /// When more than one output has been changed but not all
277 /// (after the outputs have been updated of course!)
278 /// DO NOT PASS reaction = false OR WILL NOT WORK PROPERLY
279 /// ** USER INTENDED **
280 virtual void bbSignalOutputModification( const std::vector<std::string>&
282 bool reaction = true);
283 //==================================================================
291 //==================================================================
292 /// @name Common inputs / outputs to all boxes
294 /// Returns the value of the input 'BoxProcessMode'
295 std::string bbGetInputBoxProcessMode() { return bbmBoxProcessMode; }
296 /// Sets the value of the input 'BoxProcessMode'
297 void bbSetInputBoxProcessMode(std::string a) { bbmBoxProcessMode = a; }
298 /// The possible values of the input 'BoxProcessMode'
306 /// Returns the "decoded" value of the input "BoxProcessMode"
307 BoxProcessModeValue bbGetBoxProcessModeValue() const;
308 /// Returns true iff the input 'BoxProcessMode' is set to 'Reactive' (or a synonym)
309 virtual bool bbBoxProcessModeIsReactive() const;
310 /// Returns true iff the input 'BoxProcessMode' is set to 'Always' (or a synonym)
311 virtual bool bbBoxProcessModeIsAlways() const;
313 /// Returns the value of the input 'BoxExecute'
314 Void bbGetInputBoxExecute() { return Void(); }
315 /// Sets the value of the input 'BoxExecute'
316 void bbSetInputBoxExecute(Void = 0) {}
318 /// Returns the value of the output 'BoxChange'
319 Void bbGetOutputBoxChange() { return Void(); }
320 /// Sets the value of the output 'BoxChange'
321 void bbSetOutputBoxChange(Void = 0) { }
323 //==================================================================
328 virtual void bbPrintHelp(BlackBox::Pointer parentblackbox,
329 int detail, int level
332 /// Does nothing here : overloaded in ComplexBlackBox
333 void bbInsertHTMLGraph( std::ofstream& s,
337 const std::string& output_dir,
342 //==================================================================
343 /// @name Window related methods
345 virtual void bbSetShown(bool) {}
346 virtual bool bbIsShown() { return false; }
348 //==================================================================
350 //JCP changed to public 09-06-09
351 //==================================================================
352 /// @name Manage the execution
354 static bool bbGlobalGetSomeBoxExecuting();
355 static void bbGlobalSetSomeBoxExecuting(bool b);
357 static void bbGlobalSetFreezeExecution(bool b);
358 static bool bbGlobalGetFreezeExecution();
360 static void bbGlobalAddToExecutionList( BlackBox::Pointer b );
361 static void bbGlobalProcessExecutionList();
370 //==================================================================
371 /// @name User redefinable methods
372 /// Virtual methods which can be redefined by inherited classes
376 //==================================================================
377 /// User can redefine this method to set
378 /// the default values of the box inputs and outputs
379 /// (it is called in the box constructor)
380 virtual void bbUserSetDefaultValues() {}
382 /// User can redefine this method to initialize what must be
383 /// initialized for the box to work, for example allocate dynamic data.
384 /// It is called once and only once before any call to bbUserCreateWidget
385 /// or bbUserProcess.
386 /// What has been allocated here must be desalocated in
387 /// bbFinalizeProcessing
388 virtual void bbUserInitializeProcessing() {}
390 /// User must redefine this method to uninitialize what has been
391 /// initialized in bbUserInitializeProcessing,
392 /// typically desallocate memory that has been allocated dynamically.
393 /// It is called in the box destructor if and only if (iff)
394 /// bbUserInitializeProcessing has been called previously.
395 virtual void bbUserFinalizeProcessing() {}
397 virtual void bbUserOnShow() {}
399 //==================================================================
401 //==================================================================
406 //==================================================================
408 /// Write Graphviz-dot description in file.
409 /// Here dumps a single box description (i/o) but overloaded
410 /// in ComplexBlackBox to dump the internal pipeline representation
411 /// recursing into internal boxes descriptions if level>0.
412 /// detail = 1 : draw inputs and outputs (do not draw otherwise)
413 /// instanceOrtype = true : draw inputs and outputs VALUES
414 /// (uses bbGetInputAsString / bbGetOutputAsString which use adaptors)
415 /// If relative_link is true then creates relative hrefs
416 virtual void bbWriteDotFileBlackBox(FILE *ff,
417 BlackBox::Pointer parentblackbox,
418 int detail, int level,
420 bool relative_link );
421 /// Auxiliary method for bbWriteDotFileBlackBox
422 virtual void bbWriteDotInputOutputName(FILE *ff,
424 int detail, int level);
428 virtual BlackBox::Pointer bbFindBlackBox(const std::string &blackboxname)
429 { return BlackBox::Pointer();}
431 virtual void Check(bool recursive = true);
436 //==================================================================
437 // PROTECTED PART : ACCESSIBLE TO THE BlackBox DEVELOPER
438 // (IN INHERITED CLASSES)
439 /// Constructor that take the BlackBox's name
440 BlackBox(const std::string &name);
441 /// Constructor from an existing box (copy) with a new name
442 BlackBox(BlackBox& from, const std::string &name);
443 //==================================================================
447 //==================================================================
448 /// @name Pipeline processing methods
449 /// Methods which participate to pipeline processing.
451 //==================================================================
452 /// Recursive execution method
454 /// \param caller : The connection which invoked the method; null if called by bbExecute
455 virtual void bbRecursiveExecute(Connection::Pointer caller);
456 //==================================================================
458 //==================================================================
459 /// Updates the BlackBox inputs
460 /// Calls RecursiveExecute on all BlackBoxInputConnector
461 /// \returns The maximum of final IOStatus after each input update
462 IOStatus bbUpdateInputs();
463 //==================================================================
466 //==================================================================
467 /// Actual CreateWindow method (vitual)
468 /// Overloaded in AtomicBlacBox and descendants
469 virtual void bbCreateWindow()
471 // bbtkError("BlackBox::bbCreateWidget called : how can this happen ?");
473 //==================================================================
475 //==================================================================
476 /// Actual ShowWindow method (vitual)
477 /// Overloaded in AtomicBlacBox and descendants
478 virtual void bbShowWindow()
480 // bbtkError("BlackBox::bbShowWidget called : how can this happen ?");
482 //==================================================================
485 //==================================================================
486 /// Actual processing method (vitual)
487 /// Overloaded in AtomicBlacBox and descendants
488 virtual void bbProcess()
490 bbtkError("BlackBox::bbProcess called : how can this happen ?");
491 // this->bbUserProcess();
493 //==================================================================
495 //==================================================================
496 /// Computes the final IOStatus of inputs and outputs after processing
497 void bbComputePostProcessStatus();
499 //==================================================================
502 //==================================================================
503 /// Signals that the input whose connector is c has changed
504 /// and propagates the info downward
505 /// ** NOT USER INTENDED **
506 virtual void bbSetStatusAndPropagate(BlackBoxInputConnector* c,
508 //==================================================================
512 //==================================================================
513 /// @name Box con(des)struction / initi(fin)alization methods
516 //==================================================================
517 /// Allocates the i/o connectors of the black box
518 virtual void bbAllocateConnectors();
519 /// Desallocates the i/o connectors of the black box
520 virtual void bbDesallocateConnectors();
521 /// Copies the values of the inputs/output from the BlackBox from
522 virtual void bbCopyIOValues(BlackBox& from);
523 //==================================================================
525 //==================================================================
526 /// Initializes processing IF NEEDED.
527 /// Calls bbRecursiveInitializeProcessing if the box is in
528 /// "uninitialized" state and put it in "initialized" state.
529 /// On construction, boxes are "uninitialized".
530 /// See also bbFinalizeProcessing
531 void bbInitializeProcessing();
533 /// Finalizes processing IF NEEDED.
534 /// Calls bbRecursiveFinalizeProcessing if the box is in
535 /// "initialized" state and put it in "uninitialized" state.
536 /// On construction, boxes are "uninitialized".
537 /// See also bbInitializeProcessing
538 void bbFinalizeProcessing();
540 /// Abstract prototype of the method which
541 /// Recursively calls itself for the parent black box and then
542 /// calls bbUserInitializeProcessing for its own class.
543 /// It is redefined in each black box descendant.
544 /// Allows to call bbUserInitializeProcessing for all inherited classes
545 /// (like a constructor does)
546 virtual void bbRecursiveInitializeProcessing() {}
549 /// Abstract prototype of the method which
550 /// calls bbUserFinalizeProcessing for its own class and then
551 /// recursively calls itself for the parent black box.
552 /// It is redefined in each black box descendant.
553 /// Allows to call bbUserFinalizeProcessing for all inherited classes
554 /// (like a destructor does)
555 virtual void bbRecursiveFinalizeProcessing() {}
556 //==================================================================
559 //==================================================================
564 //==================================================================
565 friend class Connection;
566 friend class ComplexBlackBox;
568 /// Sets the parent of the BlackBox
569 void bbSetParent(BlackBox::Pointer p) { bbmParent = p; }
571 //==================================================================
572 /// @name Input/output connection/disconnection
573 /// INTERNAL METHODS used by a Connection to connect/disconnect
574 /// itself to the i/o connectors of the box
577 /// Connects the input <name> to the connection c
578 virtual void bbConnectInput( const std::string& name,
580 /// Connects the output <name> to the connection c
581 virtual void bbConnectOutput( const std::string& name,
583 /// Disconnects the input <name> from the connection c
584 virtual void bbDisconnectInput( const std::string& name,
586 /// Disconnects the output <name> from the connection c
587 virtual void bbDisconnectOutput( const std::string& name,
590 //==================================================================
592 /// Returns true if the box can "react",
593 /// which means execute in response to an input change
594 virtual bool bbCanReact() const;
600 /// Returns true iff the box is executing
601 bool bbGetExecuting() const { return bbmExecuting; }
602 /// Sets the bbmExecuting bool returned by bbGetExecuting
603 void bbSetExecuting(bool b) { bbmExecuting = b; }
609 //==================================================================
613 //==================================================================
614 /// Black box objects have a special deleter
615 /// which must take care of releasing the descriptor
616 /// **AFTER** the box is deleted
617 /// (Releasing it in the destructor may cause dl close and crash)
618 /// Black box deleter
619 /// 1) Calls the user overloadable bbDelete method
620 /// 2) Releases the box descriptor
621 struct BBTK_EXPORT Deleter : public Object::Deleter
624 int Delete(Object* p);
626 //==================================================================
628 //==================================================================
629 /// Like Object::MakePointer but returns a boost::shared_pointer which uses a BlackBox::Deleter to delete the object instead of the default Object::Deleter
631 static boost::shared_ptr<U> MakeBlackBoxPointer(U* s, bool lock = false)
633 return MakePointer(s,BlackBox::Deleter(),lock);
635 //==================================================================
637 //==================================================================
638 /// Effective deletion method called by the Deleter.
639 /// The default implementation is to issue 'delete this'
640 /// but it can be redefined in inherited classes to handle special deletion mechanisms (e.g. ref counting, private destructors, such as vtk objects deletion with method Delete, etc.).
641 /// \return The number of remaining references on the object after the call (if meaningfull...): used by bbtk to warn a user if another smart pointing system is still holding the object...
643 //JCP 21-09-20 09 delete this throws and exception change due to compiler version changing and boost version
644 virtual int bbDelete() {// delete this;
646 //==================================================================
649 //==================================================================
651 //==================================================================
653 //==================================================================
655 /// Is the box initialized ?
657 /// Is the box executing ?
659 /// The name of the black-box
661 /// The name of the package to which it belongs
662 std::string bbmPackageName;
663 /// The box processing mode
664 /// 0 : "Pipeline" mode
665 /// 1 : "Always" mode
666 /// 2 : "Reactive" mode
667 std::string bbmBoxProcessMode;
668 /// The parent of the black box in the ComplexBlackBox hierarchy
669 BlackBox::WeakPointer bbmParent;
670 //==================================================================
673 //==================================================================
675 /// Map that contains the output connectors of the black box
676 OutputConnectorMapType mOutputConnectorMap;
677 /// Map that contains the input connectors of the black box
678 InputConnectorMapType mInputConnectorMap;
679 //==================================================================
687 /// Convenient macro to create output observer callbacks (freehand functions) from object and method pointer (see samples/SampleOutputObserver)
688 #define BBTK_MAKE_OUTPUT_OBSERVER(OBJECT,METHOD) \
689 boost::bind( METHOD, OBJECT, _1, _2, _3)