]> Creatis software - bbtk.git/blob - kernel/src/bbtkExecuter.cxx
*** empty log message ***
[bbtk.git] / kernel / src / bbtkExecuter.cxx
1 /*=========================================================================
2          
3   Program:   bbtk
4   Module:    $RCSfile: bbtkExecuter.cxx,v $ $
5   Language:  C++
6   Date:      $Date: 2008/04/09 11:16:57 $
7   Version:   $Revision: 1.17 $
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  *  \file 
20  *  \brief class Executer: level 0 of script execution (code)
21  */
22
23 #include "bbtkExecuter.h"
24 #include "bbtkMessageManager.h"
25 #include "bbtkFactory.h"
26 #include "bbtkUtilities.h"
27 #include <fstream>
28
29 #ifdef _USE_WXWIDGETS_
30 #include <wx/textdlg.h>
31 #endif
32
33 #include "bbtkWxBlackBox.h"
34
35 #include "bbtkConfigurationFile.h"
36
37 namespace bbtk
38 {
39   //=======================================================================
40   Executer::Executer()
41     : 
42     mFactory(0),
43     mRootPackage(0),
44     mRootCBB(0),
45     mNoExecMode(false),
46     mDialogMode(NoDialog)
47   {
48     bbtkDebugMessageInc("Kernel",9,"Executer::Executer()" <<std::endl);
49     mFactory = new Factory;
50     mFactory->SetExecuter(this);
51     Reset();
52     bbtkDebugDecTab("Kernel",9);
53   }
54   //=======================================================================
55
56   //=======================================================================
57   Executer::~Executer()
58   {
59      bbtkDebugMessageInc("Kernel",9,"Executer::~Executer()" <<std::endl);
60      if (mRootCBB) 
61      {
62         mRootPackage->UnRegisterBlackBox("workspace");
63         mRootCBB->UnReference();
64      }
65      if (mRootPackage)
66      {
67         GetFactory()->UnLoadPackage("user");
68      }
69      delete mFactory;
70
71      bbtkDebugDecTab("Kernel",9);
72   }
73   //=======================================================================
74
75   //=======================================================================
76    /// Loads a package
77     void Executer::LoadPackage(const std::string &name )
78    {
79      GetFactory()->LoadPackage(name);
80    }
81   //=======================================================================
82
83   //=======================================================================
84     /// Unloads a package
85     void Executer::UnLoadPackage(const std::string &name )
86     {
87       GetFactory()->UnLoadPackage(name);
88     }
89   //=======================================================================
90
91   //=======================================================================
92   void Executer::Reset()
93   {
94     bbtkDebugMessageInc("Kernel",9,"Executer::Reset()" <<std::endl);
95
96     GetFactory()->CheckPackages();
97
98     // The 'user' package must be closed before all other 
99     // because box destructors must not be unloaded when bb are deleted!
100     // Similarly, the 'workspace' CBB must be destroyed before 
101     // all user defined CBB otherwise any instance 
102     // of a user CBB that is in the 'workspace' would try to 
103     // access a user CBB descriptor which has been previously freed
104     if (mRootCBB)
105     {
106       mRootPackage->UnRegisterBlackBox(mRootCBB->GetTypeName());
107       mRootCBB->UnReference();
108     }
109     if (mRootPackage)
110     {
111        GetFactory()->UnLoadPackage("user");
112     }
113     GetFactory()->Reset();
114
115     // Create user package
116     mRootPackage = new Package("user","internal to bbi",
117                            "User defined black boxes",
118                            "",
119                            BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
120     // Create user workspace
121     mRootCBB = new ComplexBlackBoxDescriptor("workspace"); //,f);
122     mRootCBB->Reference();
123     mRootCBB->SetFactory(GetFactory());
124     mRootCBB->AddToAuthor("bbi (internal)");
125     mRootCBB->AddToDescription("User's workspace");
126     mOpenDefinition.push_back(CBBDefinition(mRootCBB,"user"));
127     // Register it into the user package
128     mRootPackage->RegisterBlackBox(mRootCBB);
129     // Insert the user package in the factory
130     GetFactory()->InsertPackage(mRootPackage);
131     // And in the list of open packages
132     mOpenPackage.push_back(mRootPackage);
133
134
135     GetFactory()->CheckPackages();
136
137     bbtkDebugDecTab("Kernel",9);
138   }
139   //=======================================================================
140
141   //=======================================================================
142   /// changes the workspace name
143   void Executer::SetWorkspaceName( const std::string& n )
144   {
145     mRootPackage->ChangeBlackBoxName( mRootCBB->GetTypeName(), n );
146   }
147   //=======================================================================
148
149   //=======================================================================
150   void Executer::BeginPackage (const std::string &name)
151   {
152      bbtkDebugMessageInc("Kernel",9,"Executer::BeginPackage(\""<<name<<"\")"
153                         <<std::endl);
154      Package* p;
155      try 
156       {
157          p = GetFactory()->GetPackage(name);
158       }
159     catch (Exception e)
160       {
161          p = new Package(name,
162                          "",
163                          "",
164                          "",
165                          BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
166          GetFactory()->InsertPackage(p);
167       }
168      mOpenPackage.push_back(p);
169   }
170   //=======================================================================
171
172   //=======================================================================
173   void Executer::EndPackage()
174   {
175     if (mOpenPackage.size()>1) mOpenPackage.pop_back();
176   }
177   //=======================================================================
178
179   //=======================================================================
180   void Executer::Define (const std::string &name,
181                          const std::string &pack,
182                          const std::string &scriptfilename)
183   {
184     bbtkDebugMessageInc("Kernel",9,"Executer::Define(\""<<name<<
185                         ","<<pack<<"\")"
186                         <<std::endl);
187
188     ComplexBlackBoxDescriptor* b = new ComplexBlackBoxDescriptor(name);
189     b->SetFactory(GetFactory());
190     b->SetScriptFileName(scriptfilename);
191     mOpenDefinition.push_back( CBBDefinition( b, pack ) );
192     
193     bbtkDebugDecTab("Kernel",9);
194   }
195   //=======================================================================
196
197   //=======================================================================
198   /// Sets the file name to use for the current definition
199   /// (Used to set it after the Define command)
200   void Executer::SetCurrentFileName (const std::string &name )
201   {
202     mOpenDefinition.back().box->SetScriptFileName(name);
203   }
204   //=======================================================================
205
206   //=======================================================================
207   void Executer::EndDefine ()
208   {
209     bbtkDebugMessageInc("Kernel",9,"Executer::EndDefine(\""
210                         <<Current()->GetTypeName()<<"\")" 
211                         <<std::endl);
212     // Does current package exist ?
213     Package* p;
214     std::string pname(mOpenDefinition.back().package);
215     if (pname.size()>0)
216       {
217         try
218           {
219             p = GetFactory()->GetPackage(pname);
220           }
221         catch (Exception e)
222           {
223             p = new Package(pname,
224                             "",
225                             "",
226                             "",
227                             BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
228             GetFactory()->InsertPackage(p);
229           }
230       }
231     else
232       {
233         p = mOpenPackage.back();
234       }
235     p->RegisterBlackBox(Current());
236     
237     mOpenDefinition.pop_back();
238   }
239   //======================================================================= 
240
241   //=======================================================================  
242   void Executer::Kind(const std::string& kind)
243   {
244     if (kind=="ADAPTOR")
245       {
246         Current()->AddToCategory("adaptor");
247         Current()->SetKind(bbtk::BlackBoxDescriptor::ADAPTOR);
248       }
249     else if (kind=="DEFAULT_ADAPTOR")
250       {
251         Current()->AddToCategory("adaptor");
252         Current()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_ADAPTOR);
253       }
254     if (kind=="WIDGET_ADAPTOR")
255       {
256         Current()->AddToCategory("adaptor");
257         Current()->SetKind(bbtk::BlackBoxDescriptor::WIDGET_ADAPTOR);
258       }
259     else if (kind=="DEFAULT_WIDGET_ADAPTOR")
260       {
261         Current()->AddToCategory("adaptor");
262         Current()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_WIDGET_ADAPTOR);
263       }
264     else
265       {
266         bbtkError("Unknown box kind : '"<<kind<<"'. "
267                   <<"Valid kinds are 'ADAPTOR','DEFAULT_ADAPTOR',"
268                   <<"'WIDGET_ADAPTOR','DEFAULT_WIDGET_ADAPTOR'");
269       }
270   }
271   //=======================================================================
272
273   //=======================================================================
274   void Executer::Create ( const std::string& nodeType, 
275                           const std::string& nodeName)
276   {
277      Current()->Add(nodeType,nodeName);
278   }
279   //=======================================================================
280
281   //=======================================================================
282   void Executer::Destroy(const std::string &boxName)
283   {
284     bbtkError("Executer::Destroy : NOT IMPLEMENTED !");
285   }
286   //=======================================================================
287
288   //=======================================================================
289   void Executer::Connect (const std::string &nodeFrom,
290                           const std::string &outputLabel,
291                           const std::string &nodeTo, 
292                           const std::string &inputLabel)
293   {
294     Current()->Connect(nodeFrom, outputLabel, nodeTo, inputLabel);
295   }
296   //=======================================================================
297
298   //=======================================================================
299   void Executer::Execute (const std::string &nodeName) 
300   {
301     // if in root
302      if (Current()==mRootCBB) 
303      {
304         if (!mNoExecMode) 
305         {
306            Current()->GetPrototype()->bbGetBlackBox(nodeName)->bbExecute(true);
307         }
308      }
309      else 
310      {
311         Current()->AddToExecutionList(nodeName) ;
312      }
313   }
314   //=======================================================================
315
316   //=======================================================================
317   void Executer::DefineInput ( const std::string &name,
318                                const std::string &box,
319                                const std::string &input,
320                                const std::string& help)
321   {
322     // If the input is defined in the Root box
323     if (Current()==mRootCBB) 
324       {
325       // If the dialog mode is set to NoDialog
326       // and the user passed the name in the Inputs map 
327       // then the associated value is set to the box.input
328       // This is the way command line parameters are passed to the Root box
329          if (mDialogMode == NoDialog) 
330          {
331          // find if name is in mInputs
332             std::map<std::string,std::string>::iterator i;
333             i = mInputs.find(name);
334             if (i!=mInputs.end()) {
335                Set(box,input,(*i).second);
336             }
337          }
338         // If the dialog mode is set to TextDialog
339         // The user is prompted for the value
340         else if (mDialogMode == TextDialog) 
341         {
342            std::cout << name << "=";
343            std::string ans;
344            std::cin >> ans;
345            Set(box,input,ans);
346         }
347 #ifdef _USE_WXWIDGETS_
348        // If the dialog mode is set to GraphicalDialog
349        // A dialog box is pop up
350        else if (mDialogMode == GraphicalDialog) 
351        {
352           std::string mess("Enter the value of '");
353           mess += name;
354           mess += "' (";
355           mess += help;
356           mess += ")";
357           std::string title(name);
358           title += " ?";
359           std::string ans = wx2std ( wxGetTextFromUser( std2wx (mess), std2wx(title)));
360           Set(box,input,ans); 
361        }
362 #endif
363     }
364
365     Current()->DefineInput(name,box,input,help);
366
367   }
368   //=======================================================================
369
370   //=======================================================================
371    void Executer::DefineOutput ( const std::string &name,
372                                  const std::string &box,
373                                  const std::string &output,
374                                  const std::string& help)
375   {
376     Current()->DefineOutput(name,box,output,help);
377   }
378   //=======================================================================
379
380   //=======================================================================
381   void Executer::Set (const std::string &box,
382                       const std::string &input,
383                       const std::string &value)
384   {
385     BlackBox* b = Current()->GetPrototype()->bbGetBlackBox(box);
386     // Looks for the adaptor
387
388     if ( b->bbGetInputType(input) !=  typeid(std::string) ) 
389       {
390          BlackBox* a =
391            GetFactory()->NewAdaptor(typeid(std::string),
392                                     b->bbGetInputType(input),
393                                     "tmp");
394          if (!a) 
395            {
396              bbtkError("No <"<<
397                        TypeName(b->bbGetInputType(input))
398                        <<"> to <std::string> found");
399            }
400          std::string v(value);
401          a->bbSetInput("In",v);
402          a->bbExecute();
403          b->bbSetInput(input,a->bbGetOutput("Out"));
404          a->bbDelete();
405       }
406     else 
407       {
408       std::string v(value);
409       b->bbSetInput(input,v);
410       }
411   }
412   //=======================================================================
413
414   //=======================================================================
415   std::string Executer::Get(const std::string &box,
416                             const std::string &output)
417   {
418     BlackBox* b = Current()->GetPrototype()->bbGetBlackBox(box);
419     // Looks for the adaptor
420     if (b->bbGetOutputType(output) != typeid(std::string)) 
421       {
422         BlackBox* a =
423           GetFactory()->NewAdaptor(
424                                    b->bbGetOutputType(output),
425                                    typeid(std::string),
426                                    "tmp");
427         if (!a) 
428           {
429             bbtkError("No <"<<
430                       TypeName(b->bbGetOutputType(output))
431                       <<"> to <std::string> found");
432           }
433         b->bbExecute();
434         
435         a->bbSetInput("In",b->bbGetOutput(output));
436         a->bbExecute();
437         std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
438         //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
439         //   std::cout << a->bbGetOutput("Out").unsafe_get<std::string>() 
440         //             << std::endl;
441         //std::string v(value);
442         //b->bbSetInput(input,a->bbGetOutput("Out"));
443         a->bbDelete();
444         return r;
445       }
446     else
447       {
448         b->bbExecute();
449         return b->bbGetOutput(output).unsafe_get<std::string>();
450         // std::string v = *((std::string*)b->bbGetOutput(output)) ;
451         // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>() 
452         //   << std::endl;
453         // b->bbSetInput(input,&v);
454       }
455   }
456   //=======================================================================
457
458   //=======================================================================
459   void Executer::Author(const std::string &authorName)
460   {
461     Current()->AddToAuthor(authorName,Current()==mRootCBB);
462   }
463   //=======================================================================
464
465   //=======================================================================
466   void Executer::Category(const std::string &category)
467   {
468     Current()->AddToCategory(category,Current()==mRootCBB);
469   }
470   //=======================================================================
471
472   //=======================================================================
473   void Executer::Description(const std::string &d)
474   {
475     Current()->AddToDescription(d,Current()==mRootCBB);
476   }
477   //=======================================================================
478
479   //=======================================================================
480   /// prints the list of the boxes of the current descriptor
481   void Executer::PrintBoxes()
482   {
483     bbtkMessageInc("Help",1,"The black box descriptor \""
484                    <<Current()->GetTypeName()<<"\" contains : "<<std::endl);
485     Current()->PrintBlackBoxes();
486     bbtkDecTab("Help",1);
487  }
488   //=======================================================================
489
490   //=======================================================================
491   std::string Executer::ShowGraph(const std::string &nameblackbox, 
492                                   const std::string &detailStr, 
493                                   const std::string &levelStr,
494                                   const std::string &output_html,
495                                   const std::string &custom_header,
496                                   const std::string &custom_title,
497                                   bool system_display )
498   {
499     int detail  =       atoi(detailStr.c_str());
500     int level   =       atoi(levelStr.c_str());
501
502     std::string filename_rootHtml (output_html) ;
503     std::string simplefilename_rootHtml ( Utilities::get_file_name(output_html));
504
505     bool relative_link = true;
506
507     // No output provided : automatic generation
508     if (output_html.length() == 0)
509       {
510         // Don't pollute the file store with  "temp_dir" directories ...    
511         std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
512         
513         char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
514         
515         std::string directory = default_doc_dir; 
516         if (c != '/' && c !='\\') directory = directory + "/";
517         directory = directory +  "temp_dir";    
518         
519         filename_rootHtml = directory + "/" + "User.html";
520         simplefilename_rootHtml = "User.html" ;
521
522         // Creating directory
523         std::string command0("mkdir \"" +directory + "\"");
524         system( command0.c_str() );
525
526         relative_link = false;
527       }
528
529     Package* p;
530     try
531     {
532        p = GetFactory()->GetPackage(nameblackbox);
533     }
534     catch (Exception e)
535     {
536        p = mRootPackage;
537     }
538     // Generating documentation-help of workspace
539     p->SetDocURL(filename_rootHtml);
540     p->SetDocRelativeURL(simplefilename_rootHtml);
541
542     p->CreateHtmlPage(filename_rootHtml,"bbi","user package",custom_header,custom_title,detail,level,relative_link);
543
544     std::string page = filename_rootHtml;
545     /*
546     try 
547     {
548        ShowGraphTypes(nameblackbox);
549     }
550     catch (bbtk::Exception a)
551     {
552        std::cout <<"EXC"<<std::endl;
553        page = ShowGraphInstances(nameblackbox,detail,level,system_display);
554     }
555     */
556     return page;
557   }
558   //=======================================================================
559
560   //=======================================================================
561   /// Generate a png file with the actual pipeline (Graphviz-dot needed)
562   std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
563                                            bool system_display)
564   {
565
566     BlackBox* blackbox=NULL;
567     if (nameblackbox==".")
568     {
569        blackbox=Current()->GetPrototype();
570     }
571     else
572     {
573        blackbox = Current()->GetPrototype()->bbFindBlackBox(nameblackbox);
574     }
575     
576     std::string page;
577
578     if (blackbox)
579       {      
580         // Don't pollute the file store with  "temp_dir" directories ...
581         std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
582         char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
583
584         std::string directory = default_doc_dir; 
585         if (c != '/' && c !='\\') directory = directory + "/";
586
587         directory = directory +  "temp_dir";
588         //std::string directory("temp_dir");
589         std::string filename(directory + "/" + "bbtk_graph_pipeline");
590         std::string filename_html(filename+".html");
591         std::string command0("mkdir \""+directory + "\"");
592
593 #if defined(_WIN32)
594         std::string command2("start ");
595 #else 
596         std::string command2("gnome-open ");
597 #endif
598
599         command2=command2+filename_html;
600         page = filename_html;
601         // 1. Generate Html Diagram
602         std::ofstream s;
603         s.open(filename_html.c_str());
604         if (s.good()) 
605           {
606             s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
607             s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
608             if ( blackbox->bbGetName()=="workspacePrototype" )
609               {
610                 s << "<center>Current workspace</center>";
611               } else {
612               s << "<center>" << blackbox->bbGetName()<< "</center>";
613             } 
614
615             blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
616             s << "</body></html>\n";
617           }
618         s.close();
619         
620         // 2. Starting Browser
621         if (system_display) system( command2.c_str() );      
622       } 
623     else 
624       {
625         bbtkMessageInc("Help",1,"No black box: \""
626                        <<nameblackbox<<"\" " <<std::endl);
627       }
628     return page;
629   }
630   //=======================================================================
631
632   //=======================================================================
633   void Executer::ShowRelations(const std::string &nameblackbox, 
634                                const std::string &detailStr, 
635                                const std::string &levelStr)
636   {
637     bool found=false;
638     
639     int detail = atoi(detailStr.c_str());
640     int level  = atoi(levelStr.c_str());
641     BlackBox* blackbox=NULL;
642     if (nameblackbox.compare(".")==0)
643       {
644         blackbox=Current()->GetPrototype();
645       } 
646     else 
647       {
648         blackbox = Current()->GetPrototype()->bbFindBlackBox(nameblackbox);
649       }
650     
651     if (blackbox)
652       {
653         found=true;
654         blackbox->bbShowRelations(blackbox,detail,level); //,mFactory);
655       }
656     
657     if (!found) 
658       {
659         bbtkError("Blackbox Name not found.. <"  <<nameblackbox<<">");
660       }
661   }
662   //=======================================================================
663
664   //=======================================================================
665   /// sets the level of message
666   void Executer::SetMessageLevel(const std::string &kind,
667                                  int level)
668   {
669     bbtk::MessageManager::SetMessageLevel(kind,level);
670   }
671   //=======================================================================
672
673   //=======================================================================
674   /// Prints help on the messages
675   void  Executer::HelpMessages()
676   {
677     bbtk::MessageManager::PrintInfo();
678   }
679   //=======================================================================
680
681   //=======================================================================
682   ///
683   void Executer::Print(const std::string &str)
684   {  
685     if (GetNoExecMode() &&  (Current()==mRootCBB) ) return;
686     if (Current()!=mRootCBB) return;
687
688     bbtkDebugMessageInc("Interpreter",9,"Interpreter::Print(\""<<str<<"\")"<<std::endl);
689
690  // TO DO :
691  // InterpretLine ("load std")
692  // InterpretLine("new ConcatStrings _C_ ") -> trouver un nom unique : # commande 
693  // InterpretLine("new Print _P_") 
694  // InterpretLine("connect _C_.Out _P_.In")
695  // int num = 1
696  
697
698     std::vector<std::string> chains;
699     std::string delimiters("$");
700
701     // Skip delimiters at beginning.
702     std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
703     bool is_text = true;
704     if (lastPos>0) is_text = false;
705
706     // Find first delimiter.
707     std::string::size_type pos     = str.find_first_of(delimiters, lastPos);
708
709     while (std::string::npos != pos || std::string::npos != lastPos)
710     {
711        if (is_text) 
712        {
713           // Found a text token, add it to the vector.
714           chains.push_back(str.substr(lastPos, pos - lastPos));
715  // std::string token = str.substr(lastPos, pos - lastPos)
716  // InterpretLine("set _C_.In%num% %token%")
717  
718        }
719        else 
720        {
721
722        // is an output (between $$) : decode 
723          std::string tok,box,output;
724          tok = str.substr(lastPos, pos - lastPos);
725          Utilities::SplitAroundFirstDot(tok,box,output);
726          chains.push_back( Get(box,output) );
727
728 // InterpretLine("connect %tok% _C_.In%num%") 
729
730        }
731         // Skip delimiters.  Note the "not_of"
732        lastPos = str.find_first_not_of(delimiters, pos);
733         // Find next delimiter
734        pos = str.find_first_of(delimiters, lastPos);
735     //
736        is_text = !is_text;
737 // num ++;
738      }
739 // InterpretLine("exec _P_")
740 // if (IS_IN_WORKSPACE) InterpretLine("delete _C_; delete _P_");
741
742     std::vector<std::string>::iterator i;
743     for (i= chains.begin(); i!=chains.end(); ++i) 
744       {
745         //  bbtkMessage("Echo",1,*i);
746         Utilities::SubsBackslashN(*i);
747         bbtkMessage("Output",1,*i);
748       }
749     bbtkMessage("Output",1,std::endl);
750   }
751
752 }//namespace