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