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