1 /*=========================================================================
3 Module: $RCSfile: bbtkBlackBox.h,v $
5 Date: $Date: 2011/03/03 14:33:13 $
6 Version: $Revision: 1.32 $
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)
66 struct Void { Void(int = 0) {} };
70 class BlackBoxOutputConnector;
72 class BBTK_EXPORT BlackBox : public Object
74 BBTK_ABSTRACT_OBJECT_INTERFACE(BlackBox);
79 //==================================================================
81 //==================================================================
82 typedef boost::signals::trackable OutputChangeObserverType;
83 typedef boost::signal<void (bbtk::BlackBox::Pointer,
85 IOStatus)> OutputChangeSignalType;
86 typedef OutputChangeSignalType::slot_function_type
87 OutputChangeCallbackType;
89 /// The type of map of output connector pointers
90 typedef std::map<std::string, BlackBoxOutputConnector*>
91 OutputConnectorMapType;
92 /// The type of map of input connector pointers
93 typedef std::map<std::string, BlackBoxInputConnector*>
94 InputConnectorMapType;
95 //==================================================================
98 //==================================================================
99 /// @name Pipeline processing methods
100 /// Methods which participate to pipeline processing.
102 /// Main processing method of the box.
103 virtual void bbExecute(bool force = false);
105 //==================================================================
111 //==================================================================
112 /// Returns a pointer on a clone of the box with name <name>
113 virtual BlackBox::Pointer bbClone(const std::string& name) = 0;
114 //==================================================================
117 //==================================================================
118 /// @name General accessors
119 /// Methods which give access to general informations on the box
122 /// Returns the pointer on the descriptor of the box
123 virtual BlackBoxDescriptor::Pointer bbGetDescriptor() const = 0;
125 /// Returns the Name of the Type of the BlackBox
126 const std::string& bbGetTypeName() const
127 { return bbGetDescriptor()->GetTypeName(); }
130 /// Returns the name of the BlackBox (instance)
131 const std::string& bbGetName() const { return bbmName; }
133 /// Returns the full name of the BlackBox (instance+type)
134 virtual std::string bbGetFullName() const;
136 /// Returns the name with the name of the parent prepended if any
137 virtual std::string bbGetNameWithParent() const;
139 /// Returns the parent of the BlackBox, i.e the BlackBox that contains it (0 if none)
140 BlackBox::Pointer bbGetParent() const { return bbmParent.lock(); }
143 //==================================================================
147 //==================================================================
148 /// @name Inputs/Outputs related methods
149 /// Methods related to the box inputs and outputs
152 /// Returns true iff the BlackBox has an input of name label
153 virtual bool bbHasInput(const std::string& label) const;
154 /// Gets the input type of a given label
155 virtual TypeInfo bbGetInputType( const std::string &label ) const;
156 /// Gets the status of the input called <name>
157 IOStatus bbGetInputStatus( const std::string &name ) const
158 { return mInputConnectorMap.find(name)->second->GetStatus(); }
159 /// Gets the data of the input called <name>
160 virtual Data bbGetInput( const std::string &name ) = 0;
161 /// Gets the data of the input called <name> as a string using an Adaptor if possible (else returns empty string)
162 std::string bbGetInputAsString( const std::string &input);
165 /// Sets the data of the input called <name>.
166 /// If update_time is false then does not update ChangeTime of input
167 virtual void bbSetInput( const std::string &name, Data data,
168 bool update_time = true ) = 0;
169 /// [SYSTEM]: Sets the data of the input called <name> which **MUST* be a pointer
170 virtual void bbBruteForceSetInputPointer( const std::string &name,
172 bool update_time = true) =0;
175 /// Returns true iff the BlackBox has an output of name label
176 virtual bool bbHasOutput(const std::string& label) const;
177 /// Gets the output type of a given label
178 virtual TypeInfo bbGetOutputType( const std::string &label ) const;
179 /// Gets the data of the output called <name>
180 virtual Data bbGetOutput( const std::string &name ) = 0;
181 /// Gets the data of the output called <name> as a string using an Adaptor if possible (else returns empty string)
182 std::string bbGetOutputAsString( const std::string &output ); //,Factory *factory);
184 /// Sets the data of the output called <name>
185 virtual void bbSetOutput( const std::string &name, Data data) = 0;
188 /// Returns the input connectors map
189 InputConnectorMapType& bbGetInputConnectorMap()
190 { return mInputConnectorMap; }
191 /// Returns the input connectors map (const)
192 const InputConnectorMapType& bbGetInputConnectorMap() const
193 { return mInputConnectorMap; }
194 /// Returns the input connector
195 BlackBoxInputConnector& bbGetInputConnector(const std::string& n)
196 { return *(mInputConnectorMap.find(n)->second); }
197 /// Returns the input connector (const)
198 const BlackBoxInputConnector& bbGetInputConnector(const std::string& n) const
199 { return *(mInputConnectorMap.find(n)->second); }
202 /// Returns the output connectors map
203 OutputConnectorMapType& bbGetOutputConnectorMap()
204 { return mOutputConnectorMap; }
205 /// Returns the output connectors map (const)
206 const OutputConnectorMapType& bbGetOutputConnectorMap() const
207 { return mOutputConnectorMap; }
208 /// Returns the output connector
209 BlackBoxOutputConnector& bbGetOutputConnector(const std::string& n)
210 { return *(mOutputConnectorMap.find(n)->second); }
211 /// Returns the output connector (const)
212 const BlackBoxOutputConnector& bbGetOutputConnector(const std::string& n) const
213 { return *(mOutputConnectorMap.find(n)->second); }
216 //==================================================================
218 /// Prints the Help on the BlackBox type
219 virtual void bbGetHelp(bool full=true) const;
223 //==================================================================
224 /// @name Output signals / observers related methods
225 /// Methods related to signals emitted by outputs and the
228 //==================================================================
229 /// Adds the function f to the list of functions to call when
230 /// the output changes.
231 /// f is of type ChangeCallbackType which is basically:
232 /// void (*ChangeCallbackType)(bbtk::BlackBox::Pointer,
233 /// const std::string&,
235 /// To pass a member function 'f' of an instance 'c' of a class 'C'
236 /// as callback you have to 'bind' it, i.e. call:
237 /// bbAddOutputObserver ( "Out", boost::bind( &C::f , c, _1, _2, _3 ) );
238 /// The convenience macro BBTK_BIND_OUTPUT_OBSERVER ( c, C::f ) does it for you
239 void bbAddOutputObserver(const std::string& output_name,
240 OutputChangeCallbackType f);
242 /// Removes the function f from the list of functions to call when
243 /// the output changes (TO WRITE)
244 void bbRemoveOutputObserver(const std::string& output_name,
245 OutputChangeCallbackType f);
246 //==================================================================
249 //==================================================================
250 /// Signals that the BlackBox outputs have been modified
251 /// (without marking the box as MODIFIED because its output state is ok : don't care if you understand : use it !).
252 /// This method should be used by widgets in response
253 /// to user interaction when **ALL** outputs have been modified
254 /// (after the outputs has been updated !).
255 /// DO NOT PASS reaction = false OR WILL NOT WORK PROPERLY
256 /// ** USER INTENDED **
257 virtual void bbSignalOutputModification(bool reaction = true);
258 /// Signals that the BlackBox output "output_name" has been modified
259 /// (without marking the box as MODIFIED because its output state is ok : don't care if you understand : use it !).
260 /// This method should be used by widgets in response to user interaction
261 /// only when **ONE** output has been modified
262 /// (after the output has been updated !)
263 /// DO NOT PASS reaction = false OR WILL NOT WORK PROPERLY
264 /// ** USER INTENDED **
265 virtual void bbSignalOutputModification( const std::string& output_name,
266 bool reaction = true);
267 /// Signals that the BlackBox vector of outputs "output_name"
268 /// have been modified.
269 /// Should be used when more than ONE output is modified but not ALL
270 /// (optimization issue).
271 /// (without marking the box as MODIFIED because its output state is ok).
272 /// This method should be used by widgets in response to user interaction
273 /// When more than one output has been changed but not all
274 /// (after the outputs have been updated of course!)
275 /// DO NOT PASS reaction = false OR WILL NOT WORK PROPERLY
276 /// ** USER INTENDED **
277 virtual void bbSignalOutputModification( const std::vector<std::string>&
279 bool reaction = true);
280 //==================================================================
288 //==================================================================
289 /// @name Common inputs / outputs to all boxes
291 /// Returns the value of the input 'BoxProcessMode'
292 std::string bbGetInputBoxProcessMode() { return bbmBoxProcessMode; }
293 /// Sets the value of the input 'BoxProcessMode'
294 void bbSetInputBoxProcessMode(std::string a) { bbmBoxProcessMode = a; }
295 /// The possible values of the input 'BoxProcessMode'
305 /// Returns the "decoded" value of the input "BoxProcessMode"
306 BoxProcessModeValue bbGetBoxProcessModeValue() const;
307 /// Returns true iff the input 'BoxProcessMode' is set to 'Reactive' (or a synonym)
308 virtual bool bbBoxProcessModeIsReactive() const;
309 /// Returns true iff the input 'BoxProcessMode' is set to 'Always' (or a synonym)
310 virtual bool bbBoxProcessModeIsAlways() const;
312 /// Returns the value of the input 'BoxExecute'
313 Void bbGetInputBoxExecute() { return Void(); }
314 /// Sets the value of the input 'BoxExecute'
315 void bbSetInputBoxExecute(Void = 0) {}
317 /// Returns the value of the output 'BoxChange'
318 Void bbGetOutputBoxChange() { return Void(); }
319 /// Sets the value of the output 'BoxChange'
320 void bbSetOutputBoxChange(Void = 0) { }
322 //==================================================================
324 virtual void bbPrintHelp(BlackBox::Pointer parentblackbox,
325 int detail, int level
328 /// Does nothing here : overloaded in ComplexBlackBox
329 void bbInsertHTMLGraph( std::ofstream& s,
333 const std::string& output_dir,
338 //==================================================================
339 /// @name Window related methods
341 virtual void bbSetShown(bool) {}
342 virtual bool bbIsShown() { return false; }
344 //==================================================================
346 //JCP changed to public 09-06-09
347 //==================================================================
348 /// @name Manage the execution
350 static bool bbGlobalGetSomeBoxExecuting();
351 static void bbGlobalSetSomeBoxExecuting(bool b);
353 static void bbGlobalSetFreezeExecution(bool b);
354 static bool bbGlobalGetFreezeExecution();
356 static void bbGlobalAddToExecutionList( BlackBox::Pointer b );
357 static void bbGlobalProcessExecutionList();
364 //==================================================================
365 /// @name User redefinable methods
366 /// Virtual methods which can be redefined by inherited classes
369 //==================================================================
370 /// User can redefine this method to set
371 /// the default values of the box inputs and outputs
372 /// (it is called in the box constructor)
373 virtual void bbUserSetDefaultValues() {}
375 /// User can redefine this method to initialize what must be
376 /// initialized for the box to work, for example allocate dynamic data.
377 /// It is called once and only once before any call to bbUserCreateWidget
378 /// or bbUserProcess.
379 /// What has been allocated here must be desalocated in
380 /// bbFinalizeProcessing
381 virtual void bbUserInitializeProcessing() {}
383 /// User must redefine this method to uninitialize what has been
384 /// initialized in bbUserInitializeProcessing,
385 /// typically desallocate memory that has been allocated dynamically.
386 /// It is called in the box destructor if and only if (iff)
387 /// bbUserInitializeProcessing has been called previously.
388 virtual void bbUserFinalizeProcessing() {}
390 virtual void bbUserOnShow() {}
392 //==================================================================
394 //==================================================================
397 //==================================================================
399 /// Write Graphviz-dot description in file.
400 /// Here dumps a single box description (i/o) but overloaded
401 /// in ComplexBlackBox to dump the internal pipeline representation
402 /// recursing into internal boxes descriptions if level>0.
403 /// detail = 1 : draw inputs and outputs (do not draw otherwise)
404 /// instanceOrtype = true : draw inputs and outputs VALUES
405 /// (uses bbGetInputAsString / bbGetOutputAsString which use adaptors)
406 /// If relative_link is true then creates relative hrefs
407 virtual void bbWriteDotFileBlackBox(FILE *ff,
408 BlackBox::Pointer parentblackbox,
409 int detail, int level,
411 bool relative_link );
412 /// Auxiliary method for bbWriteDotFileBlackBox
413 virtual void bbWriteDotInputOutputName(FILE *ff,
415 int detail, int level);
417 virtual BlackBox::Pointer bbFindBlackBox(const std::string &blackboxname)
418 { return BlackBox::Pointer();}
420 virtual void Check(bool recursive = true);
422 //==================================================================
423 // PROTECTED PART : ACCESSIBLE TO THE BlackBox DEVELOPER
424 // (IN INHERITED CLASSES)
425 /// Constructor that take the BlackBox's name
426 BlackBox(const std::string &name);
427 /// Constructor from an existing box (copy) with a new name
428 BlackBox(BlackBox& from, const std::string &name);
429 //==================================================================
433 //==================================================================
434 /// @name Pipeline processing methods
435 /// Methods which participate to pipeline processing.
437 //==================================================================
438 /// Recursive execution method
440 /// \param caller : The connection which invoked the method; null if called by bbExecute
441 virtual void bbRecursiveExecute(Connection::Pointer caller);
442 //==================================================================
444 //==================================================================
445 /// Updates the BlackBox inputs
446 /// Calls RecursiveExecute on all BlackBoxInputConnector
447 /// \returns The maximum of final IOStatus after each input update
448 IOStatus bbUpdateInputs();
449 //==================================================================
452 //==================================================================
453 /// Actual CreateWindow method (vitual)
454 /// Overloaded in AtomicBlacBox and descendants
455 virtual void bbCreateWindow()
457 // bbtkError("BlackBox::bbCreateWidget called : how can this happen ?");
459 //==================================================================
461 //==================================================================
462 /// Actual ShowWindow method (vitual)
463 /// Overloaded in AtomicBlacBox and descendants
464 virtual void bbShowWindow()
466 // bbtkError("BlackBox::bbShowWidget called : how can this happen ?");
468 //==================================================================
471 //==================================================================
472 /// Actual processing method (vitual)
473 /// Overloaded in AtomicBlacBox and descendants
474 virtual void bbProcess()
476 bbtkError("BlackBox::bbProcess called : how can this happen ?");
477 // this->bbUserProcess();
479 //==================================================================
481 //==================================================================
482 /// Computes the final IOStatus of inputs and outputs after processing
483 void bbComputePostProcessStatus();
485 //==================================================================
488 //==================================================================
489 /// Signals that the input whose connector is c has changed
490 /// and propagates the info downward
491 /// ** NOT USER INTENDED **
492 virtual void bbSetStatusAndPropagate(BlackBoxInputConnector* c,
494 //==================================================================
498 //==================================================================
499 /// @name Box con(des)struction / initi(fin)alization methods
502 //==================================================================
503 /// Allocates the i/o connectors of the black box
504 virtual void bbAllocateConnectors();
505 /// Desallocates the i/o connectors of the black box
506 virtual void bbDesallocateConnectors();
507 /// Copies the values of the inputs/output from the BlackBox from
508 virtual void bbCopyIOValues(BlackBox& from);
509 //==================================================================
511 //==================================================================
512 /// Initializes processing IF NEEDED.
513 /// Calls bbRecursiveInitializeProcessing if the box is in
514 /// "uninitialized" state and put it in "initialized" state.
515 /// On construction, boxes are "uninitialized".
516 /// See also bbFinalizeProcessing
517 void bbInitializeProcessing();
519 /// Finalizes processing IF NEEDED.
520 /// Calls bbRecursiveFinalizeProcessing if the box is in
521 /// "initialized" state and put it in "uninitialized" state.
522 /// On construction, boxes are "uninitialized".
523 /// See also bbInitializeProcessing
524 void bbFinalizeProcessing();
526 /// Abstract prototype of the method which
527 /// Recursively calls itself for the parent black box and then
528 /// calls bbUserInitializeProcessing for its own class.
529 /// It is redefined in each black box descendant.
530 /// Allows to call bbUserInitializeProcessing for all inherited classes
531 /// (like a constructor does)
532 virtual void bbRecursiveInitializeProcessing() {}
535 /// Abstract prototype of the method which
536 /// calls bbUserFinalizeProcessing for its own class and then
537 /// recursively calls itself for the parent black box.
538 /// It is redefined in each black box descendant.
539 /// Allows to call bbUserFinalizeProcessing for all inherited classes
540 /// (like a destructor does)
541 virtual void bbRecursiveFinalizeProcessing() {}
542 //==================================================================
545 //==================================================================
548 //==================================================================
549 friend class Connection;
550 friend class ComplexBlackBox;
552 /// Sets the parent of the BlackBox
553 void bbSetParent(BlackBox::Pointer p) { bbmParent = p; }
555 //==================================================================
556 /// @name Input/output connection/disconnection
557 /// INTERNAL METHODS used by a Connection to connect/disconnect
558 /// itself to the i/o connectors of the box
561 /// Connects the input <name> to the connection c
562 virtual void bbConnectInput( const std::string& name,
564 /// Connects the output <name> to the connection c
565 virtual void bbConnectOutput( const std::string& name,
567 /// Disconnects the input <name> from the connection c
568 virtual void bbDisconnectInput( const std::string& name,
570 /// Disconnects the output <name> from the connection c
571 virtual void bbDisconnectOutput( const std::string& name,
574 //==================================================================
576 /// Returns true if the box can "react",
577 /// which means execute in response to an input change
578 virtual bool bbCanReact() const;
580 /// Returns true iff the box is executing
581 bool bbGetExecuting() const { return bbmExecuting; }
582 /// Sets the bbmExecuting bool returned by bbGetExecuting
583 void bbSetExecuting(bool b) { bbmExecuting = b; }
587 //==================================================================
591 //==================================================================
592 /// Black box objects have a special deleter
593 /// which must take care of releasing the descriptor
594 /// **AFTER** the box is deleted
595 /// (Releasing it in the destructor may cause dl close and crash)
596 /// Black box deleter
597 /// 1) Calls the user overloadable bbDelete method
598 /// 2) Releases the box descriptor
599 struct BBTK_EXPORT Deleter : public Object::Deleter
602 int Delete(Object* p);
604 //==================================================================
606 //==================================================================
607 /// Like Object::MakePointer but returns a boost::shared_pointer which uses a BlackBox::Deleter to delete the object instead of the default Object::Deleter
609 static boost::shared_ptr<U> MakeBlackBoxPointer(U* s, bool lock = false)
611 return MakePointer(s,BlackBox::Deleter(),lock);
613 //==================================================================
615 //==================================================================
616 /// Effective deletion method called by the Deleter.
617 /// The default implementation is to issue 'delete this'
618 /// 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.).
619 /// \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...
621 //JCP 21-09-20 09 delete this throws and exception change due to compiler version changing and boost version
622 virtual int bbDelete() { delete this;
624 //==================================================================
627 //==================================================================
629 //==================================================================
631 //==================================================================
633 /// Is the box initialized ?
635 /// Is the box executing ?
637 /// The name of the black-box
639 /// The name of the package to which it belongs
640 std::string bbmPackageName;
641 /// The box processing mode
642 /// 0 : "Pipeline" mode
643 /// 1 : "Always" mode
644 /// 2 : "Reactive" mode
645 std::string bbmBoxProcessMode;
646 /// The parent of the black box in the ComplexBlackBox hierarchy
647 BlackBox::WeakPointer bbmParent;
648 //==================================================================
651 //==================================================================
653 /// Map that contains the output connectors of the black box
654 OutputConnectorMapType mOutputConnectorMap;
655 /// Map that contains the input connectors of the black box
656 InputConnectorMapType mInputConnectorMap;
657 //==================================================================
662 /// Convenient macro to create output observer callbacks (freehand functions) from object and method pointer (see samples/SampleOutputObserver)
663 #define BBTK_MAKE_OUTPUT_OBSERVER(OBJECT,METHOD) \
664 boost::bind( METHOD, OBJECT, _1, _2, _3)