]> Creatis software - creaImageIO.git/blob - src/creaImageIOGimmick.cpp
#3218 creaImageIO Feature New Normal - vtk8itk4wx3-mingw64
[creaImageIO.git] / src / creaImageIOGimmick.cpp
1 /*
2 # ---------------------------------------------------------------------
3 #
4 # Copyright (c) CREATIS (Centre de Recherche en Acquisition et Traitement de l'Image 
5 #                        pour la Santé)
6 # Authors : Eduardo Davila, Frederic Cervenansky, Claire Mouton
7 # Previous Authors : Laurent Guigues, Jean-Pierre Roux
8 # CreaTools website : www.creatis.insa-lyon.fr/site/fr/creatools_accueil
9 #
10 #  This software is governed by the CeCILL-B license under French law and 
11 #  abiding by the rules of distribution of free software. You can  use, 
12 #  modify and/ or redistribute the software under the terms of the CeCILL-B 
13 #  license as circulated by CEA, CNRS and INRIA at the following URL 
14 #  http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html 
15 #  or in the file LICENSE.txt.
16 #
17 #  As a counterpart to the access to the source code and  rights to copy,
18 #  modify and redistribute granted by the license, users are provided only
19 #  with a limited warranty  and the software's author,  the holder of the
20 #  economic rights,  and the successive licensors  have only  limited
21 #  liability. 
22 #
23 #  The fact that you are presently reading this means that you have had
24 #  knowledge of the CeCILL-B license and that you accept its terms.
25 # ------------------------------------------------------------------------
26 */
27
28 #include <creaImageIOGimmick.h>
29
30 #include <boost/filesystem.hpp>
31 #include <boost/algorithm/string.hpp>
32
33 //#include "io.h"
34 #ifndef PATH_MAX // If not defined yet : do it 
35 #  define PATH_MAX 2048
36 #endif
37 #include <creaImageIOGimmick.h>
38
39 #if defined(_WIN32)
40 #pragma warning(disable: 4996)
41 #endif
42
43 #ifdef _DEBUG
44 #define new DEBUG_NEW
45 #endif
46
47
48 namespace creaImageIO
49 {
50   //==============================================================
51   Gimmick::Gimmick()
52     : mImageAdder(0)
53   {    
54   RegisterGimmickMessageTypes();
55         mSettings               = NULL;
56         mSynchronizer   = NULL;
57         mLocalDescpName = "localdatabase_Descriptor.dscp";
58         mLocalDBName    = "Local database";
59   }
60   //==============================================================
61
62
63   //==============================================================
64   Gimmick::~Gimmick()
65   {
66          if(mSettings!=NULL)
67           {
68                 mSettings->writeSettingsFile();
69                 delete mSettings;
70           }
71         if(mSynchronizer!=NULL)
72           {
73                 delete mSynchronizer;
74           }
75   }
76   //==============================================================
77   
78   //==============================================================
79   void Gimmick::Initialize(const std::string i_namedescp, const std::string i_namedb)
80   {
81           mLocalDescpName       = i_namedescp;
82           mLocalDBName          = i_namedb;
83           Initialize();
84   }
85
86   //==============================================================
87   void Gimmick::Initialize()
88   {
89         std::string i_nameDB = mLocalDBName;
90     // Create the UserSettings dir if does not exist
91     CreateUserSettingsDirectory();
92     // Sets the current directory to the home dir
93     mCurrentDirectory =  GetHomeDirectory();
94     mSynchronizer= new Synchronizer( GetUserSettingsDirectory()+"share/creaImageIO/" );
95     mSettings  = new Settings(mCurrentDirectory);
96     std::string dbpath = GetLocalDatabasePath();
97     // Create or open local database
98     std::string dpath= mCurrentDirectory + "/.creaImageIO/share/creaImageIO/" + mLocalDescpName;
99     boost::algorithm::replace_all( dpath,
100                                    INVALID_FILE_SEPARATOR , 
101                                    VALID_FILE_SEPARATOR);
102     mLocalDatabase = createDB(i_nameDB, dpath, dbpath);
103     // Add it to the TreeHandlerMap
104     mTreeHandlerMap[i_nameDB] = mLocalDatabase;
105     //Add additional DB from user Settings
106     addDBSettings();    
107   }
108
109    ///////////////////////////////////////////////////////////////////////
110    // add DB to TreeHandler Map                                         //
111    // @param i_name : DB name                                           //
112    // @param i_location : DB location                                   //
113    // return : -                                                        //
114   ////////////////////////////////////////////////////////////////////////
115  void Gimmick::addDB(const std::string &i_name, 
116                      const std::string &i_location)
117         {
118                 if(mTreeHandlerMap.find(i_name) == mTreeHandlerMap.end())
119                 {
120                         mTreeHandlerMap[i_name] = new SQLiteTreeHandler(i_location);
121                         mTreeHandlerMap[i_name]->Open(true);
122                         mSettings->addDB(i_location);
123                 }
124         }
125
126   ///////////////////////////////////////////////////////////////////////////
127   // create a DB from a attributes descriptor file for medical images      //
128   // @param i_name : DB name                                                                                       //
129   // @param i_locDesc : location of descriptor file                                                //
130   // @param i_locDB : location of DB                                                                       //
131   // return : the SQLiteTreeHandler object on DB                                                   //
132         /////////////////////////////////////////////////////////////////////////
133         SQLiteTreeHandler* Gimmick::createDB(const std::string &i_name,
134                                              const std::string &i_locDesc,
135                                              const std::string &i_locDB)
136   {
137      SQLiteTreeHandler* sqlTreeH( new SQLiteTreeHandler(i_locDB) );
138     // Create or open local database
139     if (! boost::filesystem::exists(i_locDB) )
140      {
141          std::string mess = "Local database '";
142          mess += i_locDB;
143          mess += "' does not exist : creating it";
144          GimmickMessage(1,mess<<std::endl);
145          
146                  // CREATING DB STRUCTURE
147          sqlTreeH->GetTree().GetDescriptor().createDescriptorfromFile(i_locDesc);
148          if ( ! sqlTreeH->Create(true) )
149          {
150                 GimmickError("ERROR CREATING '"<<i_locDB<<"'");
151          }
152          sqlTreeH->SetAttribute(0,"Name",i_name);
153          } else {
154                 /// Open and test it
155                 
156                 GimmickDebugMessage(1,"Opening local database '" <<i_locDB<< "' " << std::endl);
157                 if ( !sqlTreeH->Open(true) )
158                 {
159                         GimmickError("ERROR OPENING '"<<i_locDB<<"'");
160                 }
161         }
162         return sqlTreeH;
163   }
164
165   //==============================================================
166   void Gimmick::Finalize()
167   {
168           if(mTreeHandlerMap.size() >0)
169           {
170                 // delete SQLiteTreeHandler Object
171                 for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
172                                                                                                         it!= mTreeHandlerMap.end(); 
173                                                         ++it)
174                 {
175                         delete it->second;
176                 } // for
177           } // if
178   }
179   //==============================================================
180
181   //================================================================
182   // file separator
183 #if defined(_WIN32)
184 #define VALID_FILE_SEPARATOR "\\"
185 #define INVALID_FILE_SEPARATOR "/"
186 #else
187 #define INVALID_FILE_SEPARATOR "\\"
188 #define VALID_FILE_SEPARATOR "/"
189 #endif
190   //================================================================
191
192   //================================================================
193   const std::string& Gimmick::GetHomeDirectory()
194   {
195     if (mHomeDirectory.size()==0) 
196       {
197 #if defined(_WIN32)
198         mHomeDirectory = getenv("USERPROFILE");
199 #elif defined(__GNUC__)
200         mHomeDirectory = getenv("HOME");
201 #endif
202       }
203     return mHomeDirectory;
204   }
205   //================================================================
206   const std::string& Gimmick::GetUserSettingsDirectory()
207   {
208     if (mUserSettingsDirectory.size()==0) 
209       {
210         mUserSettingsDirectory = GetHomeDirectory();
211         mUserSettingsDirectory += "/.creaImageIO/";
212         boost::algorithm::replace_all( mUserSettingsDirectory, 
213                                        INVALID_FILE_SEPARATOR , 
214                                        VALID_FILE_SEPARATOR);
215       }
216     return mUserSettingsDirectory;
217   }
218   //================================================================
219
220
221   //================================================================
222   const std::string& Gimmick::GetLocalDatabasePath()
223   {
224     if (mLocalDatabasePath.size()==0) 
225       {
226         mLocalDatabasePath = GetUserSettingsDirectory();
227         mLocalDatabasePath += "share/creaImageIO/";
228         mLocalDatabasePath += mLocalDBName;
229         mLocalDatabasePath +=".sqlite3";
230         boost::algorithm::replace_all( mLocalDatabasePath,
231                                        INVALID_FILE_SEPARATOR , 
232                                        VALID_FILE_SEPARATOR);
233       }
234     return mLocalDatabasePath;    
235   }
236
237   //========================================================================
238
239   //========================================================================
240   void Gimmick::CreateUserSettingsDirectory()
241   {
242           
243          // std::string st("C:/Documents and Settings/cervenansky/.gimmick/");
244          //     boost::algorithm::replace_all( st, 
245                 //                     INVALID_FILE_SEPARATOR , 
246                 //                     VALID_FILE_SEPARATOR);
247                 //const boost::filesystem::path mpath(st);
248 //C:\Documents and Settings\cervenansky\.gimmick");
249           //if ( !boost::filesystem::exists( path ) )             return ;
250          //  boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
251          //  for ( boost::filesystem::directory_iterator itr( path );  itr != end_itr;  ++itr )
252          // {
253                 //// If is directory & recurse : do recurse
254                 //      if ( boost::filesystem::is_directory(itr->status()) )
255                 //      return;
256          //  }
257
258           //JCP settings dir 02/10/2009
259           const std::string settingsdirectory = GetUserSettingsDirectory();
260                 //boost::algorithm::replace_all( mUserSettingsDirectory, 
261                                 //       INVALID_FILE_SEPARATOR , 
262                                 //       VALID_FILE_SEPARATOR);
263 ;//("E:\frederic");
264                   //("C:\\Documents and Settings\\cervenansky\\.gimmick\\"); // settingsdirectory );
265                 bool isdir = false;
266            isdir = boost::filesystem::is_directory(settingsdirectory); // settingsdirectory );
267     if (! isdir )
268       {
269         GimmickMessage(1,"Directory '"<<GetUserSettingsDirectory()<<"' "
270                        << "does not exist : creating it"<<std::endl);
271         
272         if ( ! boost::filesystem::create_directory( GetUserSettingsDirectory() ) )
273           {
274             GimmickError("ERROR CREATING '"<<GetUserSettingsDirectory()<<"'");
275           }
276       }
277
278         std::string setDir=GetUserSettingsDirectory();
279         boost::algorithm::replace_all( setDir,
280                                        INVALID_FILE_SEPARATOR , 
281                                        VALID_FILE_SEPARATOR);
282         setDir+="share/";
283         boost::filesystem::create_directory( setDir );
284         setDir+="creaImageIO/";
285         boost::filesystem::create_directory( setDir );
286         setDir+=mLocalDescpName;
287
288         if(!boost::filesystem::is_regular(setDir))
289         {
290                 char name[PATH_MAX];
291                 crea::System::GetAppPath(name,PATH_MAX);
292                 std::cout<<name<<std::endl;
293                 
294                 std::string path=name;
295                 path=path.substr(0,path.size()-1);
296                 path=path.substr(0,path.find_last_of("/"));
297                 //Creating directories
298
299 // The following stuff works on Linux, NOT CHECKED on Windows // JPR
300                 
301 #if defined(_WIN32)             
302                 path+="/bin/share/creaImageIO/";
303 #endif
304
305 #if defined (LINUX)
306                 path+="/../share/creaImageIO/";
307 #endif  
308 #if defined(__APPLE__)
309                 path+="/../../../../share/creaImageIO/";
310 #endif 
311
312
313 path+= mLocalDescpName;
314                 
315                 std::cout <<"From: " << path   <<std::endl;
316                 std::cout <<"To: "   << setDir <<std::endl;
317                 boost::algorithm::replace_all(  path,
318                                                 INVALID_FILE_SEPARATOR , 
319                                                 VALID_FILE_SEPARATOR);
320                 boost::filesystem::copy_file(path,setDir);
321         }
322           
323   }
324   //========================================================================
325
326
327   //========================================================================
328   /// Sets message level
329   void Gimmick::SetMessageLevel(int l)
330   {
331     SetGimmickMessageLevel(l);
332   }
333   //========================================================================
334
335   //========================================================================
336   /// Sets message level
337   void Gimmick::SetDebugMessageLevel(int l)
338   {
339     SetGimmickDebugMessageLevel(l);
340   }
341   //========================================================================
342
343   //========================================================================
344   /// Returns the tree handler with the given name
345   TreeHandler* Gimmick::GetTreeHandler(const std::string& name) const 
346   {  
347     TreeHandlerMapType::const_iterator i;
348     i = GetTreeHandlerMap().find(name);
349     if ( i == GetTreeHandlerMap().end() )
350       {
351         GimmickError("TreeHandler '"<<name<<"' does not exist");
352       }
353     return i->second;
354   }
355
356   //========================================================================
357   /// Add the files to the tree handler
358   void Gimmick::AddFiles(const std::string& d, 
359                         const std::vector<std::string>& filenames)
360   {
361     GimmickMessage(2,"Adding files to '"<<d<<"'"<<std::endl);
362         mImageAdder.SetCurrentDatabase(d);
363         mImageAdder.SetTreeHandler(GetTreeHandler(d));
364         mImageAdder.SetSynchronizer(mSynchronizer);
365         mImageAdder.AddFiles(filenames);        
366   }
367   //========================================================================
368
369   //========================================================================
370   /// Add a dir to the local database
371   void Gimmick::AddDir(const std::string& d, const std::string& f, 
372                        bool recurse)
373   {
374         GimmickMessage(2,"Adding dir '"<<f<<"' to '"<<d<<"' recurse:" <<recurse<<std::endl);
375         TreeHandler * handler=GetTreeHandler(d);
376         mImageAdder.SetCurrentDatabase(d);
377         mImageAdder.SetTreeHandler(handler);
378         mImageAdder.SetSynchronizer(mSynchronizer);
379         mImageAdder.AddDirectory(f,recurse);  
380   }
381
382   //========================================================================
383
384   //========================================================================
385   void Gimmick::RemoveFile(const std::string& d, 
386                            tree::Node* node)
387   {
388           mImageAdder.SetCurrentDatabase(d);
389           mImageAdder.SetSynchronizer(mSynchronizer);
390           mImageAdder.RemoveFile(node);
391   }
392   //========================================================================
393
394   //void Gimmick::Anonymize(std::vector<std::string>i_files)  {  }
395   //========================================================================
396  
397   void Gimmick::CopyFiles(const std::vector<std::string>& filenames, const std::string& d )
398   {
399           TreeHandler * handler=GetTreeHandler(d);
400           mImageAdder.SetCurrentDatabase(d);
401           mImageAdder.SetTreeHandler(handler);
402           mImageAdder.SetSynchronizer(mSynchronizer);
403           mImageAdder.CopyFiles(filenames, mSettings->getValue(SETTINGS_COPY_PATH));
404   }
405
406   //========================================================================
407  
408   std::string Gimmick::Synchronize(const std::string& d, bool repair, bool checkAttributes)
409   {
410           TreeHandler * handler=GetTreeHandler(d);
411           mImageAdder.SetCurrentDatabase(d);
412           mImageAdder.SetTreeHandler(handler);
413           mImageAdder.SetSynchronizer(mSynchronizer);
414           return mImageAdder.Synchronize(repair, checkAttributes);
415   }
416
417   //========================================================================
418   /// 
419   void Gimmick::Print(const std::string& d)
420   {
421     GetTreeHandler(d)->GetTree().Print();
422   }
423   //========================================================================
424
425   void Gimmick::GetSetting(const std::string& name, std::string& value)
426   {
427     value = mSettings->getValue(name);
428   }
429   //========================================================================
430
431   //========================================================================
432
433   void Gimmick::GetAttributes(const std::string& d, 
434                         const std::string& filename, 
435                         const std::vector<std::string>& params, 
436                         std::vector<std::string>& results)
437   {
438           TreeHandler * handler=GetTreeHandler(d);
439           mImageAdder.SetCurrentDatabase(d);
440           mImageAdder.SetTreeHandler(handler);
441           mImageAdder.SetSynchronizer(mSynchronizer);
442           mImageAdder.GetAttributes(params, filename, results);
443   }
444   //========================================================================
445
446   //========================================================================
447   // get attributes values from database  for a given file from database 
448   //========================================================================
449    void Gimmick::GetAttributes(const std::string filename, std::map<std::string, std::string> &i_res, OutputAttr i_attr)
450   {
451            if (i_attr.inside.size() > 0)
452            {
453                    std::map<std::string, std::string> map_attr;
454                    TreeHandler * handler=GetTreeHandler(i_attr.db);
455                    handler->getAllAttributes(filename, map_attr);
456                    if(i_attr.inside.front() == "ALL") // we  take all values
457                    {
458                            std::map<std::string, std::string>::iterator it = map_attr.begin();
459                            for(; it != map_attr.end(); it++)
460                            {
461                                    i_res[it->first] = it->second;
462                            } // for        
463                    } else {
464                             std::vector<std::string>::iterator it = i_attr.inside.begin();
465                             for(; it != i_attr.inside.end(); it++) 
466                                 {
467                                    i_res[(*it)] = map_attr[(*it)];
468                                 } // for   
469                    } // if ALL
470            } // if size
471   }
472
473
474   //========================================================================
475
476   void Gimmick::UpdateSetting(const std::string& name, const std::string& value)
477   {
478           mSettings->updateSetting(name,value);
479           mSettings->writeSettingsFile();
480   }
481   //========================================================================
482
483   void Gimmick::DeleteDrive(const std::string& drive)
484   {
485         for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
486                                                it!= mTreeHandlerMap.end(); 
487                                                ++it)
488            {
489                    mImageAdder.SetTreeHandler(it->second);
490                    mImageAdder.DeleteDriveFromMainDB(drive);
491            }
492         mImageAdder.SetSynchronizer(mSynchronizer);
493         mImageAdder.DeleteDriveFromOtherDB(drive);
494   }
495
496   //========================================================================
497   void Gimmick::EditField(tree::Node* node, const std::string& d, const std::string& name, const std::string& key, const std::string& val)
498   {
499         TreeHandler * handler=GetTreeHandler(d);
500         mImageAdder.SetCurrentDatabase(d);
501         mImageAdder.SetTreeHandler(handler);
502         mImageAdder.EditField(node,name,key,val);
503   }
504   //========================================================================
505
506   ////////////////////////////////////////////////////////////////////////
507   // add DB from Settings file                                          //
508   // @param : -                                                         //
509   // return : -                                                         //
510   ////////////////////////////////////////////////////////////////////////
511   void Gimmick::addDBSettings()
512   {
513
514          std::string pathSettings = mSettings->getValue(SETTINGS_DBPATH);
515          
516          // split to find all paths
517          std::vector<std::string> paths;
518          std::string separator = ";";
519          std::string::size_type last_pos = pathSettings.find_first_not_of(separator);
520          //find first separator
521          std::string::size_type pos = pathSettings.find_first_of(separator, last_pos);
522          while(std::string::npos != pos || std::string::npos != last_pos)
523          {
524                 paths.push_back(pathSettings.substr(last_pos, pos - last_pos));
525                 last_pos = pathSettings.find_first_not_of(separator, pos);
526                 pos = pathSettings.find_first_of(separator, last_pos);
527          }
528
529          std::vector<std::string>::iterator it_path = paths.begin();
530          for(; it_path != paths.end(); ++it_path)
531          {
532                  pos = it_path->find_last_of("\\");
533                  last_pos = it_path->find_last_of(".");
534                  std::string name = it_path->substr(pos +1, last_pos -pos-1 );
535                  addDB(name, it_path->c_str());
536          }
537   }     
538
539
540 ///////////////////////////////////////////////////////////////////////////////
541 // Fill attributes structure with attributes present in database (inside vector
542 // and not present (outside)
543 ///////////////////////////////////////////////////////////////////////////////
544 void Gimmick::fillVectInfos(std::vector<std::string> i_attr, OutputAttr &infos)
545 {
546         //test if a tag is present in Database descriptor
547         TreeHandler * handler=GetTreeHandler(infos.db);
548         mImageAdder.SetTreeHandler(handler);
549         std::vector<std::string>::const_iterator it = i_attr.begin();
550         for (;it != i_attr.end(); it++)
551         {
552                 if( mImageAdder.isAttributeExist((*it)) != "" ) // in DB
553                 {
554 printf("EED Gimmick::fillVectInfos inside %s\n",(*it).c_str());
555                         infos.inside.push_back((*it));
556                 } else {
557                                 infos.outside.push_back((*it)); // Need to scan again the files
558 printf("EED Gimmick::fillVectInfos outside %s\n",(*it).c_str());
559                 } // if
560         } // for
561 }
562
563 const std::string Gimmick::getSummary()
564 {
565       const AddProgress& p = GetAddProgress();
566     std::stringstream mess;
567     mess << "Dirs \tscanned\t: " << p.GetNumberScannedDirs()  << "\n";
568     mess << "Files\tscanned\t: " << p.GetNumberScannedFiles() << "\n";
569     mess << "Files\thandled\t: " << p.GetNumberHandledFiles() << "\n\n";
570     mess << "Files\tadded  \t: " << p.GetNumberAddedFiles()   << "\n\n";
571     return mess.str();
572 }
573
574 }