]> Creatis software - bbtk.git/blob - kernel/src/bbtkBlackBox.cxx
=== MAJOR RELEASE ====
[bbtk.git] / kernel / src / bbtkBlackBox.cxx
1 /*=========================================================================
2                                                                                 
3 Program:   bbtk
4 Module:    $RCSfile: bbtkBlackBox.cxx,v $
5 Language:  C++
6 Date:      $Date: 2008/04/18 12:59:15 $
7 Version:   $Revision: 1.10 $
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 #include "bbtkBlackBox.h"
25 #include "bbtkPackage.h"
26 #include "bbtkMessageManager.h"
27 #include "bbtkFactory.h"
28
29 #include "bbtkConfigurationFile.h"
30 #include "bbtkWxBlackBox.h"
31
32 #include <fstream>
33 //#include <vector>
34
35
36 namespace bbtk
37 {
38
39
40   static bool bbmgSomeBoxExecuting = false;
41   static bool bbmgFreezeExecution = false;
42   static std::set<BlackBox::Pointer> bbmgExecutionList;
43
44   //=========================================================================
45   BlackBox::Deleter::Deleter()
46   {
47   }
48   //=========================================================================
49   
50   //=========================================================================
51   void BlackBox::Deleter::Delete(Object* p)
52   {
53     BlackBox* b = dynamic_cast<BlackBox*>(p);
54     if (!b)
55       {
56         bbtkInternalError("BlackBox::Deleter::Delete("<<p->GetObjectName()
57                           <<"["<<p<<"]) : "
58                           <<"dynamic cast to BlackBox* failed !");
59       }
60     std::string name = p->GetObjectName();//b->bbGetNameWithParent();
61     bbtkDebugMessage("object",2,"##> BlackBox::Deleter(\""<<name<<"\")"<<std::endl);
62
63
64     BlackBoxDescriptor::WeakPointer desc = b->bbGetDescriptor();
65     bbtkDebugMessage("object",2,"##> BlackBox::Deleter(\""<<name<<"\") : deleting black box"<<std::endl);
66     
67     b->bbDelete();
68     
69     bbtkDebugMessage("object",2,"##> BlackBox::Deleter(\""<<name<<"\") : releasing descriptor ["<<desc.lock()<<"]"<<std::endl);
70     
71     if (!desc.expired()) 
72       {
73         Package::WeakPointer pack = desc.lock()->GetPackage();
74         if (!pack.expired()) 
75           {
76             Package::ReleaseBlackBoxDescriptor(pack,desc);
77           }
78         else 
79           {
80             bbtkDebugMessage("object",2,"##> BlackBox::Deleter(\""<<name<<"\") : descriptor package expired (was not held by a package and the box was the last instance)"<<std::endl);
81           }
82       }
83     else
84       {
85         bbtkDebugMessage("object",2,"##> BlackBox::Deleter(\""<<name<<"\") : descriptor expired : nothing to do (was not held by a package or the box is a complex black box prototype)"<<std::endl);
86       }
87     bbtkDebugMessage("object",2,"<## BlackBox::Deleter(\""<<name<<"\")"<<std::endl);
88   }
89   //=========================================================================
90
91   //=========================================================================
92   BlackBox::BlackBox(const std::string &name) 
93     : bbmName(name), 
94       bbmStatus(MODIFIED), 
95       bbmBoxProcessMode("Pipeline"),
96       bbmParent(),
97       bbmExecuting(false)
98   {
99     bbtkDebugMessage("object",4,"==> BlackBox::BlackBox(\""
100                      <<name<<"\")"<<std::endl);
101     bbtkDebugMessage("object",4,"<== BlackBox::BlackBox(\""
102                      <<name<<"\")"<<std::endl);
103   }
104   //=========================================================================
105
106
107   //=========================================================================
108   BlackBox::BlackBox(BlackBox& from, const std::string &name) 
109     : bbmName(name), 
110       bbmStatus(from.bbmStatus), 
111       bbmBoxProcessMode(from.bbmBoxProcessMode),
112       bbmParent(),
113       bbmExecuting(false)
114   {
115     bbtkDebugMessage("object",4,"==> BlackBox::BlackBox("
116                      <<from.bbGetFullName()<<",\""
117                      <<name<<"\")"<<std::endl);
118     bbtkDebugMessage("object",4,"<== BlackBox::BlackBox("
119                      <<from.bbGetFullName()<<",\""
120                      <<name<<"\")"<<std::endl);
121   }
122   //=========================================================================
123
124
125   //=========================================================================
126   BlackBox::~BlackBox()
127   {
128     bbtkDebugMessage("object",4,"==> BlackBox::~BlackBox() ["<<bbmName
129                      <<"]"<<std::endl);
130     this->bbDesallocateConnectors();
131     bbtkDebugMessage("object",4,"<== BlackBox::~BlackBox() ["<<bbmName
132                      <<"]"<<std::endl);
133   }
134   //=========================================================================
135
136
137   //=========================================================================
138   /// Main processing method of the box.
139   void BlackBox::bbExecute(bool force)
140   {
141     bbtkDebugMessageInc("Process",1,
142                         "=> BlackBox::bbExecute() ["
143                         <<bbGetFullName()<<"]"<<std::endl);
144  
145     Wx::BeginBusyCursor();
146
147     // If execution frozen : return
148     if (bbGlobalGetFreezeExecution()) 
149       {
150         bbtkDebugMessage("Process",1,
151                          " -> FreezeExecution global flag is 'true' : abort execution"<<std::endl);
152       }
153
154     // If force is true then update is triggered even if the box is UPTODATE
155     if (force) bbSetModifiedStatus();
156
157     // Calls the main recursive update method 
158     bbBackwardUpdate(Connection::Pointer());
159
160     Wx::EndBusyCursor();
161
162     bbtkDebugMessageDec("Process",1,
163                         "<= BlackBox::bbExecute() ["
164                         <<bbGetFullName()<<"]"<<std::endl);
165   }
166   //=========================================================================
167
168   //=========================================================================
169   std::string BlackBox::bbGetFullName() const
170   { 
171     return this->bbGetNameWithParent()+"<"+this->bbGetDescriptor()->GetTypeName()+">";
172   }
173   //=========================================================================
174      
175
176
177   //=========================================================================
178   /// Returns the name with the name of the parent prepended if any
179   std::string BlackBox::bbGetNameWithParent() const
180   {
181     if (bbmParent.lock()) 
182       {
183         return bbmParent.lock()->bbGetNameWithParent() + ":" + bbmName;
184       }
185     else 
186       {
187         return bbmName;
188       }
189   } 
190   //=========================================================================
191
192   //=========================================================================
193   /// Prints the Help on the BlackBox type 
194   void BlackBox::bbGetHelp(bool full) const
195   {
196     bbGetDescriptor()->GetHelp(full); 
197   }
198   //=========================================================================
199
200
201   //=========================================================================
202   /// Returns true if the UserBlackBox has an input of name name
203   bool BlackBox::bbHasInput(const std::string& name) const
204   {
205     bbtkDebugMessageInc("Kernel",8,
206                         "BlackBox::bbHasInput(\""
207                         <<name<<"\") ["<<bbGetFullName()<<"]"
208                         <<std::endl);
209     bool r = ( bbGetDescriptor()->GetInputDescriptorMap().find(name)
210                != bbGetDescriptor()->GetInputDescriptorMap().end());
211     bbtkDebugDecTab("Kernel",8);
212     return r;
213   }
214   //=========================================================================
215
216
217   //=========================================================================  
218   /// Returns true if the UserBlackBox has an output of name name
219   bool BlackBox::bbHasOutput(const std::string& name) const
220   {
221     bbtkDebugMessageInc("Kernel",8,"BlackBox::bbHasOutput(\""
222                         <<name<<"\") ["<<bbGetFullName()<<"]"<<std::endl);
223     bool r = ( bbGetDescriptor()->GetOutputDescriptorMap().find(name)
224                != bbGetDescriptor()->GetOutputDescriptorMap().end());
225     bbtkDebugDecTab("Kernel",8);
226     return r;
227   }
228   //=========================================================================
229
230
231   //=========================================================================  
232   ///  Gets the output type of a given name
233   TypeInfo BlackBox::bbGetOutputType( const std::string &name ) const 
234   {
235     bbtkDebugMessageInc("Kernel",8,
236                         "BlackBox::bbGetOutputType(\""
237                         <<name<<"\") ["<<bbGetFullName()<<"]"<<std::endl);
238     TypeInfo r = bbGetDescriptor()->GetOutputDescriptor(name)->GetTypeInfo();
239     bbtkDebugDecTab("Kernel",8); 
240     return r;
241   }
242   //=========================================================================
243
244   //=========================================================================
245   ///  Gets the input type of a given name
246   TypeInfo BlackBox::bbGetInputType( const std::string &name ) const
247   {
248     bbtkDebugMessageInc("Kernel",8,
249                         "BlackBox::bbGetInputType(\""
250                         <<name<<"\") ["<<bbGetFullName()<<"]"<<std::endl);
251     TypeInfo r = bbGetDescriptor()->GetInputDescriptor(name)->GetTypeInfo();
252     bbtkDebugDecTab("Kernel",8);
253     return r;
254   }
255   //=========================================================================
256
257
258   //=========================================================================
259   /// Allocates the i/o connectors of the black box
260   void BlackBox::bbAllocateConnectors()
261   {  
262     bbtkDebugMessageInc("Kernel",8,
263                         "BlackBox::bbAllocateConnectors() ["
264                         <<bbGetFullName()<<"]"
265                         <<std::endl);                                   
266     const BlackBoxDescriptor::InputDescriptorMapType& imap 
267       = bbGetDescriptor()->GetInputDescriptorMap(); 
268     BlackBoxDescriptor::InputDescriptorMapType::const_iterator i;       
269     for ( i = imap.begin(); i != imap.end(); ++i )                      
270       {                                                                 
271         bbtkDebugMessage("Kernel",8,"* Allocate \""<<i->first<<"\""<<std::endl);
272         bbGetInputConnectorMap()[i->second->GetName()] 
273           = new BlackBoxInputConnector(GetThisPointer<BlackBox>());
274       }                                                                 
275     const BlackBoxDescriptor::OutputDescriptorMapType& omap 
276       = bbGetDescriptor()->GetOutputDescriptorMap();                   
277     BlackBoxDescriptor::OutputDescriptorMapType::const_iterator o; 
278     for ( o = omap.begin(); o != omap.end(); ++o )
279       {                                                 
280         bbtkDebugMessage("Kernel",8,"* Allocate \""<<o->first<<"\""<<std::endl);
281         bbGetOutputConnectorMap()[o->second->GetName()] 
282           = new BlackBoxOutputConnector();
283       }
284     bbtkDebugDecTab("Kernel",8);  
285   }
286   //=========================================================================
287
288
289   //=========================================================================
290   /// Desallocates the i/o connectors of the black box
291   void BlackBox::bbDesallocateConnectors()
292   {
293     bbtkDebugMessageInc("Kernel",8,
294                         "BlackBox::bbDesallocateConnectors()"
295                         <<std::endl);                                   
296
297     InputConnectorMapType::const_iterator i;
298     for ( i = bbGetInputConnectorMap().begin();
299           i != bbGetInputConnectorMap().end(); ++i )                   
300       {                                                                 
301         bbtkDebugMessage("Kernel",8,"* Delete \""<<i->first<<"\""<<std::endl);
302         delete (i->second);
303       }                                                                 
304     OutputConnectorMapType::const_iterator o;   
305     for ( o = bbGetOutputConnectorMap().begin(); 
306           o != bbGetOutputConnectorMap().end(); ++o )                   
307       {                                                                 
308         bbtkDebugMessage("Kernel",8,"* Delete \""<<o->first<<"\""<<std::endl);         
309         delete (o->second);
310       }                                                                 
311    
312     bbtkDebugDecTab("Kernel",8);  
313
314   }
315   //=========================================================================
316
317
318   //=========================================================================
319   /// Copies the input / output values from another box
320   void BlackBox::bbCopyIOValues(BlackBox& from)
321   {
322     bbtkDebugMessageInc("Kernel",9,
323                         "BlackBox::bbCopyIOValues("
324                         <<from.bbGetFullName()<<") ["
325                         <<bbGetFullName()<<"]"<<std::endl);
326     // copies the input values
327     const BlackBoxDescriptor::InputDescriptorMapType& imap 
328       = bbGetDescriptor()->GetInputDescriptorMap(); 
329     BlackBoxDescriptor::InputDescriptorMapType::const_iterator i;       
330     for ( i = imap.begin(); i != imap.end(); ++i )                      
331       {         
332         if (! i->second->GetCopyConstruct() ) continue;
333         std::string input = i->second->GetName();
334         this->bbSetInput(input, from.bbGetInput(input) );
335       }                                                                 
336     // copies the output values
337     const BlackBoxDescriptor::OutputDescriptorMapType& omap 
338       = bbGetDescriptor()->GetOutputDescriptorMap();                   
339     BlackBoxDescriptor::OutputDescriptorMapType::const_iterator o; 
340     for ( o = omap.begin(); o != omap.end(); ++o )
341       {                                                 
342         if (! o->second->GetCopyConstruct() ) continue;
343         std::string output = o->second->GetName();
344         this->bbSetOutput(output, from.bbGetOutput(output) );
345       }
346
347     bbtkDebugDecTab("Kernel",9);
348
349   }
350   //=========================================================================
351
352
353
354   //=========================================================================
355   bool BlackBox::bbCanReact() const 
356   { 
357     return ( bbGlobalGetSomeBoxExecuting() 
358 #ifdef _USE_WXWIDGETS_
359              || Wx::IsSomeWindowAlive() 
360 #endif
361              ); 
362   }
363   //=========================================================================
364
365
366
367   //=========================================================================
368   /// User overloadable destruction method of a black box
369   void BlackBox::bbUserDelete() 
370   {   
371     bbtkDebugMessage("Process",5,
372                      "=> BlackBox::bbUserDelete() ["
373                      <<bbGetFullName()<<"]"
374                      <<" : not overloaded; using standard deletion"
375                      <<std::endl);
376     delete this;
377   }
378   //=========================================================================
379
380
381   //=========================================================================
382   BlackBox::BoxProcessModeValue BlackBox::bbGetBoxProcessModeValue() const
383   {
384     const std::string& p = bbmBoxProcessMode;
385     if ( (p == "0") ||
386          (p == "P") || (p == "p") ||
387          (p == "Pipeline") || (p == "pipeline") ) return Pipeline;
388     if ( (p == "1") ||
389          (p == "A") || (p == "a") ||
390          (p == "Always") || (p == "always") ) return Always;
391     if ( (p == "2") ||
392          (p == "R") || (p == "r") ||
393          (p == "Reactive") || (p == "reactive") ) return Reactive;
394     bbtkError(bbGetFullName()<<" : BoxProcessMode value '"<<p
395               <<"' unknown. Possible values : "
396               <<"'0'/'P'/'p'/'Pipeline'/'pipeline' | "
397               <<"'1'/'A'/'a'/'Always'/'always' | "
398               <<"'2'/'R'/'r'/'Reactive'/'reactive'"<<std::endl);
399   }
400   //=========================================================================
401   
402   //=========================================================================
403   bool  BlackBox::bbBoxProcessModeIsReactive() const
404   {
405     return (bbGetBoxProcessModeValue() == Reactive);
406   }
407   //=========================================================================
408
409   //=========================================================================
410   bool  BlackBox::bbBoxProcessModeIsAlways() const
411   {
412     return (bbGetBoxProcessModeValue() == Always);
413   }
414   //=========================================================================
415
416   //=========================================================================
417   ///  Signals that the BlackBox has been modified
418   void BlackBox::bbSetModifiedStatus(BlackBoxInputConnector* c)
419   {
420     bbtkDebugMessageInc("Process",5,
421                         "=> BlackBox::bbSetModifiedStatus("<<c<<") ["
422                         <<bbGetFullName()<<"]"<<std::endl);
423    
424     if ( (c==bbGetInputConnectorMap().find("WinHide")->second) )
425          //      && (bbCanReact()))
426       {
427         bbtkDebugMessage("Process",9,
428                          "-> Hide triggered by WinHide input change"
429                          <<std::endl);
430         this->bbHideWindow();
431         this->bbSetStatus(MODIFIED); 
432         return;
433       }
434  
435     if ( ( bbBoxProcessModeIsReactive()  ||
436            (c==bbGetInputConnectorMap().find("BoxExecute")->second))
437          && (bbCanReact() ) )
438       {
439         bbtkDebugMessage("Process",9,
440                          "-> Execution triggered by Reactive mode or BoxExecute input change"<<std::endl);
441         this->bbSetStatus(MODIFIED); 
442         bbGlobalAddToExecutionList( GetThisPointer<BlackBox>() );
443       }
444     else if ( bbGetStatus() == MODIFIED ) //! this->bbIsUptodate()) 
445       { 
446         bbtkDebugMessage("Process",5,"-> Already modified"<<std::endl);
447         bbtkDebugDecTab("Process",5);
448         return;
449       }
450     else 
451       {
452         bbtkDebugMessage("Process",5,"-> Status set to modified"<<std::endl);
453         bbtkDebugDecTab("Process",5);
454         this->bbSetStatus(MODIFIED); 
455       }
456  
457     this->bbSignalOutputModification(false);
458
459    bbtkDebugMessageDec("Process",5,
460                         "<= BlackBox::bbSetModifiedStatus("<<c<<") ["
461                         <<bbGetFullName()<<"]"<<std::endl);
462   }  
463   //=========================================================================
464
465   //=========================================================================  
466   void BlackBox::bbSignalOutputModification(bool reaction)
467   {
468     bbtkDebugMessageInc("Process",5,
469                         "=> BlackBox::bbSignalOutputModification() ["
470                         <<bbGetFullName()<<"]"<<std::endl);
471     
472     OutputConnectorMapType::iterator change = bbGetOutputConnectorMap().end();
473     OutputConnectorMapType::iterator i;
474     for ( i  = bbGetOutputConnectorMap().begin(); 
475           i != bbGetOutputConnectorMap().end(); ++i) {
476       /*     if ( i->first == "BoxChange" ) 
477         {
478           change = i;
479           continue;
480         }
481       */
482       i->second->SetModifiedStatus();
483     } 
484     //    if (change != bbGetOutputConnectorMap().end()) 
485     // change->second->SetModifiedStatus();
486
487     if (reaction) bbGlobalProcessExecutionList();
488
489     bbtkDebugMessageDec("Process",5,
490                         "<= BlackBox::bbSignalOutputModification() ["
491                         <<bbGetFullName()<<"]"<<std::endl);
492     
493   }  
494   //=========================================================================   
495   //=========================================================================  
496   void BlackBox::bbSignalOutputModification(const std::string& output,
497         bool reaction)
498   {
499     bbtkDebugMessageInc("Process",5,
500                         "=> BlackBox::bbSignalOutputModification("
501                         <<output<<") ["
502                         <<bbGetFullName()<<"]"<<std::endl);
503     
504     OutputConnectorMapType::iterator i = bbGetOutputConnectorMap().find(output);
505     if ( i == bbGetOutputConnectorMap().end() ) 
506         {
507           bbtkError("BlackBox["<<bbGetFullName()<<"]::bbSignalOutputModification("<<output<<") : unknown output");
508         }
509     i->second->SetModifiedStatus();
510     // Has to notify the output "BoxChange" also
511     if (output != "BoxChange") 
512       {
513         i = bbGetOutputConnectorMap().find("BoxChange");
514         if ( i != bbGetOutputConnectorMap().end() ) 
515           {
516             i->second->SetModifiedStatus();
517           }
518       }
519   if (reaction) bbGlobalProcessExecutionList();
520
521   bbtkDebugMessageDec("Process",5,
522                       "<= BlackBox::bbSignalOutputModification("
523                       <<output<<") ["
524                       <<bbGetFullName()<<"]"<<std::endl);
525
526   }  
527   //=========================================================================   
528   //=========================================================================  
529   void BlackBox::bbSignalOutputModification(const std::vector<std::string>& output,
530         bool reaction)
531   {
532     bbtkDebugMessageInc("Process",5,
533                         "=> BlackBox::bbSignalOutputModification(vector of outputs) ["
534                         <<bbGetFullName()<<"]"<<std::endl);
535     OutputConnectorMapType::iterator i;
536     std::vector<std::string>::const_iterator o;
537     for (o=output.begin();o!=output.end();++o) 
538       {
539         // the output "BoxChange" must be signaled **AFTER** all others
540         if (*o == "BoxChange") continue;
541         // Look for the connector
542         i = bbGetOutputConnectorMap().find(*o);
543         if ( i == bbGetOutputConnectorMap().end() ) 
544           {
545             bbtkError("BlackBox["<<bbGetFullName()<<"]::bbSignalOutputModification("<<*o<<") : unknown output");
546           }
547         i->second->SetModifiedStatus();
548       }
549     // Has to notify the output "BoxChange" also
550     i = bbGetOutputConnectorMap().find("BoxChange");
551     if ( i != bbGetOutputConnectorMap().end() ) 
552       {
553         i->second->SetModifiedStatus();
554       }
555   if (reaction) bbGlobalProcessExecutionList();
556
557    bbtkDebugMessageDec("Process",5,
558                        "<= BlackBox::bbSignalOutputModification(vector of outputs) ["
559                         <<bbGetFullName()<<"]"<<std::endl);
560
561   }  
562   //=========================================================================   
563
564   //=========================================================================
565   /// Updates the BlackBox inputs
566   /// \returns UPTODATE if all inputs are in UPTODATE status after update
567   ///          else MODIFIED 
568   IOStatus BlackBox::bbUpdateInputs(bool excludeParent)
569   {
570     bbtkDebugMessageInc("Process",4,
571                         "=> BlackBox::bbUpdateInputs() ["
572                         <<bbGetFullName()<<"]"
573                         <<std::endl);   
574
575     IOStatus s = UPTODATE;
576
577     InputConnectorMapType::iterator i;
578     for ( i = bbGetInputConnectorMap().begin(); 
579           i!= bbGetInputConnectorMap().end(); ++i) 
580       {
581         if (excludeParent && (i->first=="WinParent")) continue;
582         if (i->first=="WinHide") continue;
583         // If input type is Void : no recurse
584         //if (  bbGetDescriptor()->GetInputDescriptor(i->first)->GetTypeInfo() 
585         //      == typeid(Void) ) 
586         //  continue;
587
588         IOStatus t = i->second->BackwardUpdate();
589         if (t==MODIFIED) s = MODIFIED;
590       }
591     
592    bbtkDebugMessageDec("Process",4,
593                         "<= BlackBox::bbUpdateInputs() ["
594                         <<bbGetFullName()<<"]"
595                         <<std::endl);   
596
597
598     return s;
599   }
600   //=========================================================================
601
602  
603   //=========================================================================
604   /// Connects the input <name> to the connection c
605   void BlackBox::bbConnectInput( const std::string& name, Connection::Pointer c)
606   {
607     bbtkDebugMessageInc("Kernel",7,
608                         "BlackBox::bbConnectInput(\""<<name<<"\","<<c<<") ["
609                         <<bbGetFullName()<<"]"
610                         <<std::endl);       
611     InputConnectorMapType::iterator i = bbGetInputConnectorMap().find(name);
612     if (i==bbGetInputConnectorMap().end())
613       {
614         bbtkError("no input called '"<<name<<"'");
615       }
616     i->second->SetConnection(c);
617     
618     //  bbSetModifiedStatus();
619
620     bbtkDebugDecTab("Kernel",7);
621   }
622   //=========================================================================
623
624
625   //=========================================================================  
626   /// Connects the output <name> to the connection c
627   void BlackBox::bbConnectOutput( const std::string& name, Connection::Pointer c)
628   {
629     bbtkDebugMessageInc("Kernel",7,
630                         "BlackBox::bbConnectOutput(\""<<name<<"\","<<c<<") ["
631                         <<bbGetFullName()<<"]"<<std::endl);       
632
633     OutputConnectorMapType::iterator i = bbGetOutputConnectorMap().find(name);
634     if (i==bbGetOutputConnectorMap().end())
635       {
636         bbtkError("no output called '"<<name<<"'");
637       }
638     i->second->SetConnection(c);
639
640     bbtkDebugDecTab("Kernel",7);
641   }
642   //=========================================================================
643
644
645   //=========================================================================
646   /// Disconnects the input <name> from the connection c
647   void BlackBox::bbDisconnectInput( const std::string& name, Connection::Pointer c)
648   {
649     if (!c) return;
650     bbtkDebugMessageInc("Kernel",7,
651                         "BlackBox::bbDisconnectInput(\""<<name
652                         <<"\","<<c<<") ["
653                         <<bbGetFullName()<<"]"
654                         <<std::endl);      
655
656     InputConnectorMapType::iterator i = bbGetInputConnectorMap().find(name);
657     if (i==bbGetInputConnectorMap().end())
658       {
659         bbtkError("no input called '"<<name<<"'");
660       }
661     i->second->UnsetConnection(c);
662
663     bbtkDebugDecTab("Kernel",7);
664   }
665   //=========================================================================
666
667
668   //=========================================================================
669   /// Disconnects the output <name> from the connection c
670   void BlackBox::bbDisconnectOutput( const std::string& name, Connection::Pointer c)
671   {
672     if (!c) return;
673     bbtkDebugMessageInc("Kernel",7,
674                         "BlackBox::bbDisconnectOutput(\""<<name
675                         <<"\","<<c<<") ["
676                         <<bbGetFullName()<<"]"
677                         <<std::endl);       
678
679     OutputConnectorMapType::iterator i = bbGetOutputConnectorMap().find(name);
680     if (i==bbGetOutputConnectorMap().end())
681       {
682         bbtkError("no output called '"<<name<<"'");
683       }
684     i->second->UnsetConnection(c);
685
686     bbtkDebugDecTab("Kernel",7);
687   } 
688   //=========================================================================
689  
690
691   //=========================================================================
692   /// Virtual
693   void BlackBox::bbWriteDotInputOutputName(FILE *ff,bool inputoutput,int detail, int level)
694   {
695     fprintf(ff,"%s%p",bbGetTypeName().c_str(),this);
696   }
697   //=========================================================================
698
699
700   //=========================================================================
701   std::string BlackBox::bbGetOutputAsString( const std::string &output ) 
702   {
703     std::string v;
704     // Looks for the adaptor
705     if (bbGetOutputType(output).name() != typeid(std::string).name() ) 
706       {
707         // Look for factory 
708         Package::Pointer p = bbGetDescriptor()->GetPackage();
709         if ((p != 0) && ( ! p->GetFactorySet().empty() ) )
710           {
711             Factory::Pointer f = p->GetFactorySet().begin()->lock();
712             BlackBox::Pointer a;
713             try
714               {
715                 a = f->NewAdaptor(  
716                                   bbGetOutputType(output),
717                                   typeid(std::string),
718                                   "");
719               } catch (bbtk::Exception e) 
720               {
721               }
722             if (a){
723               //                        bbUpdate();
724               a->bbSetInput("In",bbGetOutput(output));
725               a->bbExecute();
726               v = a->bbGetOutput("Out").unsafe_get<std::string>() ;
727             } else {
728               v="? (no adaptor found)";
729             }
730           }
731         else 
732           {
733             v="? (no factory found)";
734           }
735       } 
736     else 
737       {
738         //         bbUpdate();
739         v = bbGetOutput(output).unsafe_get<std::string>() ;
740       }
741     return v;
742   }
743   //=========================================================================
744
745   //=========================================================================
746   std::string BlackBox::bbGetInputAsString( const std::string &input ) 
747   {
748     std::string v;
749     // Looks for the adaptor
750     if (bbGetInputType(input) != typeid(std::string)) 
751       {
752         // Look for factory 
753         Package::Pointer p = bbGetDescriptor()->GetPackage();
754         if ((p != 0) && ( ! p->GetFactorySet().empty() ) )
755           {
756             Factory::Pointer f = p->GetFactorySet().begin()->lock();
757             BlackBox::Pointer a;
758             try
759               {
760                 a = f->NewAdaptor(  
761                                bbGetInputType(input),
762                                typeid(std::string),
763                                "");
764               }catch (bbtk::Exception e) 
765               {
766               }
767             if (a)
768               {
769                 //                      bbUpdate();
770                 a->bbSetInput("In",bbGetInput(input));
771                 a->bbExecute();
772                 v = a->bbGetOutput("Out").unsafe_get<std::string>() ;
773               } 
774             else 
775               {
776                 v="? (no adaptor found)";
777               }
778           } 
779         else 
780           {
781             v="? (no factory found)";
782           }
783       }
784     else 
785       {
786         v = bbGetInput(input).unsafe_get<std::string>() ;
787       }
788     return v;
789   }
790   //=======================================================================
791
792   //=======================================================================
793   // Replaces substrings "<" by "["
794   void SubsBrackets ( std::string& s )
795   {
796     //   std::cout << "BEFORE=["<<s<<"]"<<std::endl;
797     std::string ss("<");
798     std::string::size_type pos = 0;
799     pos = s.find(ss,0);
800     char* cr = "[";
801     while ( pos != std::string::npos )
802       {
803         //      std::cout << "*** find one "<<std::endl;
804         s.replace(pos,1,cr,1);
805         pos = s.find(ss, pos);
806       } 
807     ss = ">";
808     pos = 0;
809     pos = s.find(ss,0);
810     cr = "]";
811     while ( pos != std::string::npos )
812       {
813         //      std::cout << "*** find one "<<std::endl;
814         s.replace(pos,1,cr,1);
815         pos = s.find(ss, pos);
816       } 
817     ss = ",";
818     pos = 0;
819     pos = s.find(ss,0);
820     cr = "-";
821     while ( pos != std::string::npos )
822       {
823         //      std::cout << "*** find one "<<std::endl;
824         s.replace(pos,1,cr,1);
825         pos = s.find(ss, pos);
826       }     //    std::cout << "AFTER=["<<s<<"]"<<std::endl;
827   }
828   //=======================================================================
829
830   //=========================================================================
831   /// Write Graphviz-dot description in file
832   void BlackBox::bbWriteDotFileBlackBox(FILE *ff,
833                                         BlackBox::Pointer parentblackbox, 
834                                         int detail, int level,
835                                         bool instanceOrtype,
836                                         bool relative_link )
837
838   { 
839     InputConnectorMapType::iterator i;
840     // label
841     std::string labelStr;
842     std::string valueStr("");
843
844         if (detail==0) {
845                 labelStr = bbGetName() ; 
846 //EED 18 Fev 2008
847                 labelStr = labelStr + "\\n[" +this->bbGetDescriptor()->GetPackage()->GetName()+"::"+ bbGetTypeName() + "]";
848         } else {
849                 labelStr = bbGetName();
850                 labelStr = labelStr + "   [" +this->bbGetDescriptor()->GetPackage()->GetName()+"::"+ bbGetTypeName() + "]  ";
851     }
852
853     SubsBrackets(labelStr);
854     if (detail==1)
855       {
856         labelStr = labelStr + " | {{ "; 
857         std::string tempStrTypeName;
858         bool tmp; 
859         tmp=false;
860         for ( i = mInputConnectorMap.begin(); i != mInputConnectorMap.end(); ++i ) 
861           {
862             if (tmp==true)
863               {
864                 labelStr=labelStr+" | ";
865               }
866             tmp=true;
867             if (instanceOrtype==true)
868               {
869                 valueStr = this->bbGetInputAsString(i->first) + " = ";
870               } 
871             const BlackBoxInputDescriptor* id = bbGetDescriptor()->GetInputDescriptor(i->first);
872             tempStrTypeName=id->GetTypeName();
873             SubsBrackets(tempStrTypeName);
874             std::string Name(i->first);
875             SubsBrackets(Name);
876             labelStr=labelStr + "<"+i->first.c_str()+"> "  + valueStr +  Name.c_str() + "  [" + tempStrTypeName.c_str() + "]";
877           }
878         labelStr=labelStr+ " } | {";
879         tmp = false;
880         OutputConnectorMapType::iterator ii;
881         for ( ii = mOutputConnectorMap.begin(); ii != mOutputConnectorMap.end(); ++ii ) 
882         {
883            if (tmp==true)
884            {
885                    labelStr=labelStr+" | ";
886            }
887            tmp = true;
888            if (instanceOrtype==true)
889            {
890                    valueStr = this->bbGetOutputAsString(ii->first) + " = ";
891            }
892            const BlackBoxOutputDescriptor* id = bbGetDescriptor()->GetOutputDescriptor(ii->first); 
893            tempStrTypeName=id->GetTypeName();
894            SubsBrackets(tempStrTypeName);
895             std::string Name(ii->first);
896             SubsBrackets(Name);
897            labelStr=labelStr+"<"+ii->first.c_str()+"> " + valueStr + Name.c_str() + "  ["+tempStrTypeName+"]";
898         }
899         labelStr = labelStr+ "      } }" ;
900 } // detail
901
902     fprintf(ff,"  " );
903     bbWriteDotInputOutputName(ff,true,detail,level);
904     std::string tmp ( bbGetTypeName() );
905     SubsBrackets(tmp);
906     std::string url;
907     if (relative_link) 
908       url = this->bbGetDescriptor()->GetPackage()->GetDocRelativeURL() + "#" + tmp;
909     else 
910       url = this->bbGetDescriptor()->GetPackage()->GetDocURL() + "#" + tmp;
911   
912     fprintf( ff , " [shape=record, URL=\"%s\",label=\"%s\"]%s\n",url.c_str(),labelStr.c_str(),";" );
913     //    std::cout  << labelStr << std::endl;
914
915     // Relation Input
916     if (GetThisPointer<BlackBox>()!=parentblackbox){
917       for ( i = mInputConnectorMap.begin(); i != mInputConnectorMap.end(); ++i ) 
918         {
919           if (i->second)
920             {
921               Connection::Pointer con = i->second->GetConnection();
922               if (con!=NULL){
923                 BlackBox::Pointer a=con->GetBlackBoxFrom();
924                 BlackBox::Pointer b=con->GetBlackBoxTo();
925                 fprintf(ff,"  ");
926                 a->bbWriteDotInputOutputName(ff,false,detail,level);
927                 if (detail==1)
928                   {
929                     fprintf(ff,":%s",con->GetBlackBoxFromOutput().c_str());
930                   }
931                 fprintf(ff,"->");
932                 b->bbWriteDotInputOutputName(ff,true,detail,level);
933                 if (detail==1)
934                   {
935                     fprintf(ff,":%s",con->GetBlackBoxToInput().c_str());
936                   }
937                 fprintf(ff,"%s\n",";");
938               }  // if con
939             } // if second
940         } // for
941     } // if parentblackbox
942   }
943   //=========================================================================
944
945
946
947
948   //=========================================================================
949   void BlackBox::bbShowRelations(BlackBox::Pointer parentblackbox, 
950                                  int detail, int level
951                                  /*,Factory *factory*/ )
952   {
953      
954     if (this->bbGetDescriptor()->GetPackage()) 
955       {
956         bbtkMessage("Help",1,"Black Box '"<<bbGetName()<<"' <"<<
957                     this->bbGetDescriptor()->GetPackage()->GetName()
958                     <<"::"<<this->bbGetDescriptor()->GetTypeName()<<">"<<std::endl);
959       }
960     else 
961       {
962         bbtkMessage("Help",1,"Black Box <::"<<this->bbGetDescriptor()->GetTypeName()<<">"<<std::endl);
963       }
964     //    bbtkMessage("Help",1," "<<GetDescription()<<std::endl);
965     //    bbtkMessage("Help",1," By : "<<GetAuthor()<<std::endl);
966
967     std::vector<std::string> iname;
968     std::vector<std::string> ivalue;
969     std::vector<std::string> iconn;
970
971     InputConnectorMapType::iterator i;
972     unsigned int namelmax = 0;
973     unsigned int valuelmax = 0;
974     unsigned int connlmax = 0;
975     for ( i = mInputConnectorMap.begin(); i != mInputConnectorMap.end(); ++i ) 
976       {
977         iname.push_back(i->first);
978         if (iname.back().size()>namelmax) namelmax = iname.back().size();
979         ivalue.push_back(bbGetInputAsString(i->first));
980         if (ivalue.back().size()>valuelmax) valuelmax = ivalue.back().size();
981         std::string s("");
982         Connection::Pointer con = i->second->GetConnection();
983         if (con!=0){
984           s = con->GetBlackBoxFrom()->bbGetName();
985           s += ".";
986           s += con->GetBlackBoxFromOutput();
987         }  // if con
988         iconn.push_back(s);
989       }
990     OutputConnectorMapType::iterator o;
991     std::vector<std::string> oname;
992     std::vector<std::string> ovalue;
993     std::vector<std::vector<std::string> > oconn;
994     for ( o = mOutputConnectorMap.begin(); o != mOutputConnectorMap.end(); ++o ) 
995       {
996         oname.push_back(o->first);
997         if (oname.back().size()>namelmax) namelmax = oname.back().size();
998         ovalue.push_back(bbGetOutputAsString(o->first));
999         if (ovalue.back().size()>valuelmax) valuelmax = ovalue.back().size();
1000         std::vector<std::string> ss;
1001         const std::vector<Connection::WeakPointer>& con 
1002           = o->second->GetConnectionVector();
1003         std::vector<Connection::WeakPointer>::const_iterator c;
1004         for (c=con.begin();c!=con.end();++c) 
1005           {
1006             std::string s;
1007             s = (*c).lock()->GetBlackBoxTo()->bbGetName();
1008             s += ".";
1009             s += (*c).lock()->GetBlackBoxToInput();
1010             ss.push_back(s);
1011         }  // if con
1012         oconn.push_back(ss);
1013       }
1014
1015     if (iname.size()) 
1016       bbtkMessage("Help",1," * Inputs : "<<std::endl);
1017     else 
1018       bbtkMessage("Help",1," * No inputs"<<std::endl);
1019
1020     std::vector<std::string>::iterator i1,i2,i3;
1021     for (i1=iname.begin(),i2=ivalue.begin(),i3=iconn.begin();
1022          i1!=iname.end(),i2!=ivalue.end(),i3!=iconn.end();
1023          ++i1,++i2,++i3)
1024       {
1025         std::string name(*i1);
1026         name += "'";
1027         name.append(1+namelmax-name.size(),' ');
1028         std::string value(*i2);
1029         value += "'";
1030         value.append(1+valuelmax-value.size(),' ');
1031         if (i3->size()) 
1032           bbtkMessage("Help",1,"    '"<<name<<" = '"<<value<<" <-- '"<<*i3<<"'"<<std::endl);
1033         else 
1034           bbtkMessage("Help",1,"    '"<<name<<" = '"<<value<<std::endl);
1035       }
1036
1037     if (oname.size()) 
1038       bbtkMessage("Help",1," * Outputs : "<<std::endl);
1039     else 
1040       bbtkMessage("Help",1," * No outputs"<<std::endl);
1041
1042     std::vector<std::vector<std::string> >::iterator i4;
1043
1044     for (i1=oname.begin(),i2=ovalue.begin(),i4=oconn.begin();
1045          i1!=oname.end(),i2!=ovalue.end(),i4!=oconn.end();
1046          ++i1,++i2,++i4)
1047       {
1048         std::string name(*i1);
1049         name += "'";
1050         name.append(1+namelmax-name.size(),' ');
1051         std::string value(*i2);
1052         value += "'";
1053         value.append(1+valuelmax-value.size(),' ');
1054         if (!(*i4).size())
1055           bbtkMessage("Help",1,"    '"<<name<<" = '"<<value<<std::endl);
1056         else 
1057           {
1058             std::string pref = "    '"+name+" = '"+value;
1059             for (i3=i4->begin();i3!=i4->end();++i3)
1060               {
1061                 bbtkMessage("Help",1,pref<<" --> '"<<*i3<<"'"<<std::endl);
1062                 pref.replace(0,pref.size(),pref.size(),' ');
1063               }
1064           }
1065       }
1066
1067    }
1068   //=========================================================================
1069
1070
1071   //=========================================================================
1072    void BlackBox::bbGlobalProcessExecutionList()
1073    {   
1074      bbtkDebugMessageInc("Process",1,
1075                          "=> BlackBox::bbGlobalProcessExecutionList()"
1076                          <<std::endl);     
1077      
1078      std::set<BlackBox::Pointer>::iterator i;
1079      for (i=bbmgExecutionList.begin();
1080           i!=bbmgExecutionList.end();
1081           ++i)
1082        {
1083          bbtkDebugMessage("Process",2,
1084                           " -> Executing "<<(*i)->bbGetFullName()<<std::endl);
1085          (*i)->bbExecute(true);
1086        }
1087      
1088      bbmgExecutionList.clear();
1089      bbtkDebugMessageDec("Process",1,
1090                          "<= BlackBox::bbGlobalProcessExecutionList()"
1091                          <<std::endl);     
1092      
1093      
1094    }
1095   //=========================================================================
1096
1097     bool BlackBox::bbGlobalGetSomeBoxExecuting()
1098         { 
1099                 return bbmgSomeBoxExecuting; 
1100         }
1101
1102     void BlackBox::bbGlobalSetSomeBoxExecuting(bool b) 
1103         { 
1104                 bbmgSomeBoxExecuting = b; 
1105         }
1106
1107     void BlackBox::bbGlobalSetFreezeExecution(bool b) 
1108         { 
1109                 bbmgFreezeExecution = b;
1110         }
1111
1112     bool BlackBox::bbGlobalGetFreezeExecution() 
1113         { 
1114                 return bbmgFreezeExecution; 
1115         }
1116
1117   void BlackBox::bbGlobalAddToExecutionList( BlackBox::Pointer b )
1118         {  
1119                 bbmgExecutionList.insert(b); 
1120         } 
1121
1122
1123   //=========================================================================
1124   // Static members initialization
1125 /*EED
1126   bool BlackBox::bbmgSomeBoxExecuting = false;
1127   bool BlackBox::bbmgFreezeExecution = false;
1128   std::set<BlackBox*> BlackBox::bbmgExecutionList;
1129 */
1130    //=========================================================================
1131
1132   //=========================================================================
1133   void BlackBox::Check(bool recursive)
1134   {
1135     bbtkMessage("Debug",1,"*** Checking Black Box "<<(void*)this<<" ["<<bbGetFullName()
1136                 <<"] ... OK"<<std::endl);
1137   }
1138   //=========================================================================
1139
1140
1141
1142 }  // EO namespace bbtk
1143
1144 // EOF
1145