]> Creatis software - creaImageIO.git/blob - src/creaImageIOGimmick.cpp
898de344fb7d5ad09037b359f308cb11ed1d22a4
[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          }
154          else 
155          {
156                 /// Open and test it
157                 
158                 GimmickDebugMessage(1,"Opening local database '" <<i_locDB<< "' " << std::endl);
159                 if ( !sqlTreeH->Open(true) )
160                 {
161                         GimmickError("ERROR OPENING '"<<i_locDB<<"'");
162                 }
163         }
164         return sqlTreeH;
165   }
166
167   //==============================================================
168   void Gimmick::Finalize()
169   {
170           if(mTreeHandlerMap.size() >0)
171           {
172                 // delete SQLiteTreeHandler Object
173                 for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
174                                                                                                         it!= mTreeHandlerMap.end(); 
175                                                         ++it)
176                 {
177                         delete it->second;
178                 }
179           }
180   }
181   //==============================================================
182
183   //================================================================
184   // file separator
185 #if defined(_WIN32)
186 #define VALID_FILE_SEPARATOR "\\"
187 #define INVALID_FILE_SEPARATOR "/"
188 #else
189 #define INVALID_FILE_SEPARATOR "\\"
190 #define VALID_FILE_SEPARATOR "/"
191 #endif
192   //================================================================
193
194   //================================================================
195   const std::string& Gimmick::GetHomeDirectory()
196   {
197     if (mHomeDirectory.size()==0) 
198       {
199 #if defined(_WIN32)
200         mHomeDirectory = getenv("USERPROFILE");
201 #elif defined(__GNUC__)
202         mHomeDirectory = getenv("HOME");
203 #endif
204       }
205     return mHomeDirectory;
206   }
207   //================================================================
208   const std::string& Gimmick::GetUserSettingsDirectory()
209   {
210     if (mUserSettingsDirectory.size()==0) 
211       {
212         mUserSettingsDirectory = GetHomeDirectory();
213         mUserSettingsDirectory += "/.creaImageIO/";
214         boost::algorithm::replace_all( mUserSettingsDirectory, 
215                                        INVALID_FILE_SEPARATOR , 
216                                        VALID_FILE_SEPARATOR);
217       }
218     return mUserSettingsDirectory;
219   }
220   //================================================================
221
222
223   //================================================================
224   const std::string& Gimmick::GetLocalDatabasePath()
225   {
226     if (mLocalDatabasePath.size()==0) 
227       {
228         mLocalDatabasePath = GetUserSettingsDirectory();
229         mLocalDatabasePath += "share/creaImageIO/";
230         mLocalDatabasePath += mLocalDBName;
231         mLocalDatabasePath +=".sqlite3";
232         boost::algorithm::replace_all( mLocalDatabasePath,
233                                        INVALID_FILE_SEPARATOR , 
234                                        VALID_FILE_SEPARATOR);
235       }
236     return mLocalDatabasePath;    
237   }
238
239   //========================================================================
240
241   //========================================================================
242   void Gimmick::CreateUserSettingsDirectory()
243   {
244           
245          // std::string st("C:/Documents and Settings/cervenansky/.gimmick/");
246          //     boost::algorithm::replace_all( st, 
247                 //                     INVALID_FILE_SEPARATOR , 
248                 //                     VALID_FILE_SEPARATOR);
249                 //const boost::filesystem::path mpath(st);
250 //C:\Documents and Settings\cervenansky\.gimmick");
251           //if ( !boost::filesystem::exists( path ) )             return ;
252          //  boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
253          //  for ( boost::filesystem::directory_iterator itr( path );  itr != end_itr;  ++itr )
254          // {
255                 //// If is directory & recurse : do recurse
256                 //      if ( boost::filesystem::is_directory(itr->status()) )
257                 //      return;
258          //  }
259
260           //JCP settings dir 02/10/2009
261           const std::string settingsdirectory = GetUserSettingsDirectory();
262                 //boost::algorithm::replace_all( mUserSettingsDirectory, 
263                                 //       INVALID_FILE_SEPARATOR , 
264                                 //       VALID_FILE_SEPARATOR);
265 ;//("E:\frederic");
266                   //("C:\\Documents and Settings\\cervenansky\\.gimmick\\"); // settingsdirectory );
267                 bool isdir = false;
268            isdir = boost::filesystem::is_directory(settingsdirectory); // settingsdirectory );
269     if (! isdir )
270       {
271         GimmickMessage(1,"Directory '"<<GetUserSettingsDirectory()<<"' "
272                        << "does not exist : creating it"<<std::endl);
273         
274         if ( ! boost::filesystem::create_directory( GetUserSettingsDirectory() ) )
275           {
276             GimmickError("ERROR CREATING '"<<GetUserSettingsDirectory()<<"'");
277           }
278       }
279
280         std::string setDir=GetUserSettingsDirectory();
281         boost::algorithm::replace_all( setDir,
282                                        INVALID_FILE_SEPARATOR , 
283                                        VALID_FILE_SEPARATOR);
284         setDir+="share/";
285         boost::filesystem::create_directory( setDir );
286         setDir+="creaImageIO/";
287         boost::filesystem::create_directory( setDir );
288         setDir+=mLocalDescpName;
289
290         if(!boost::filesystem::is_regular(setDir))
291         {
292                 char name[PATH_MAX];
293                 crea::System::GetAppPath(name,PATH_MAX);
294                 std::cout<<name<<std::endl;
295                 
296                 std::string path=name;
297                 path=path.substr(0,path.size()-1);
298                 path=path.substr(0,path.find_last_of("/"));
299                 //Creating directories
300
301 // The following stuff works on Linux, NOT CHECKED on Windows // JPR
302                 
303 #if defined(_WIN32)             
304                 path+="/bin/share/creaImageIO/";
305 #endif
306
307 #if defined (LINUX)
308                 path+="/../share/creaImageIO/";
309 #endif  
310 #if defined(__APPLE__)
311                 path+="/../../../../share/creaImageIO/";
312 #endif 
313
314
315 path+= mLocalDescpName;
316                 
317                 std::cout <<"From: " << path   <<std::endl;
318                 std::cout <<"To: "   << setDir <<std::endl;
319                 boost::algorithm::replace_all(  path,
320                                                 INVALID_FILE_SEPARATOR , 
321                                                 VALID_FILE_SEPARATOR);
322                 boost::filesystem::copy_file(path,setDir);
323         }
324           
325   }
326   //========================================================================
327
328
329   //========================================================================
330   /// Sets message level
331   void Gimmick::SetMessageLevel(int l)
332   {
333     SetGimmickMessageLevel(l);
334   }
335   //========================================================================
336
337   //========================================================================
338   /// Sets message level
339   void Gimmick::SetDebugMessageLevel(int l)
340   {
341     SetGimmickDebugMessageLevel(l);
342   }
343   //========================================================================
344
345   //========================================================================
346   /// Returns the tree handler with the given name
347   TreeHandler* Gimmick::GetTreeHandler(const std::string& name) const 
348   {  
349     TreeHandlerMapType::const_iterator i;
350     i = GetTreeHandlerMap().find(name);
351     if ( i == GetTreeHandlerMap().end() )
352       {
353         GimmickError("TreeHandler '"<<name<<"' does not exist");
354       }
355     return i->second;
356   }
357
358   //========================================================================
359   /// Add the files to the tree handler
360   void Gimmick::AddFiles(const std::string& d, 
361                         const std::vector<std::string>& filenames)
362   {
363     GimmickMessage(2,"Adding files to '"<<d<<"'"<<std::endl);
364  
365         mImageAdder.SetCurrentDatabase(d);
366         mImageAdder.SetTreeHandler(GetTreeHandler(d));
367         mImageAdder.SetSynchronizer(mSynchronizer);
368         mImageAdder.AddFiles(filenames);        
369   }
370   //========================================================================
371
372   //========================================================================
373   /// Add a dir to the local database
374   void Gimmick::AddDir(const std::string& d, const std::string& f, 
375                        bool recurse)
376   {
377         GimmickMessage(2,"Adding dir '"<<f<<"' to '"<<d<<"' recurse:"
378                          <<recurse<<std::endl);
379
380         TreeHandler * handler=GetTreeHandler(d);
381         mImageAdder.SetCurrentDatabase(d);
382         mImageAdder.SetTreeHandler(handler);
383         mImageAdder.SetSynchronizer(mSynchronizer);
384         mImageAdder.AddDirectory(f,recurse);  
385   }
386
387   //========================================================================
388
389   //========================================================================
390   void Gimmick::RemoveFile(const std::string& d, 
391                            tree::Node* node)
392   {
393           mImageAdder.SetCurrentDatabase(d);
394           mImageAdder.SetSynchronizer(mSynchronizer);
395           mImageAdder.RemoveFile(node);
396   }
397   //========================================================================
398
399   //void Gimmick::Anonymize(std::vector<std::string>i_files)  {  }
400   //========================================================================
401  
402   void Gimmick::CopyFiles(const std::vector<std::string>& filenames, const std::string& d )
403   {
404           TreeHandler * handler=GetTreeHandler(d);
405           mImageAdder.SetCurrentDatabase(d);
406           mImageAdder.SetTreeHandler(handler);
407           mImageAdder.SetSynchronizer(mSynchronizer);
408           mImageAdder.CopyFiles(filenames, mSettings->getValue(SETTINGS_COPY_PATH));
409   }
410
411   //========================================================================
412  
413   std::string Gimmick::Synchronize(const std::string& d, bool repair, bool checkAttributes)
414   {
415           TreeHandler * handler=GetTreeHandler(d);
416           mImageAdder.SetCurrentDatabase(d);
417           mImageAdder.SetTreeHandler(handler);
418           mImageAdder.SetSynchronizer(mSynchronizer);
419           return mImageAdder.Synchronize(repair, checkAttributes);
420   }
421
422   //========================================================================
423   /// 
424   void Gimmick::Print(const std::string& d)
425   {
426     GetTreeHandler(d)->GetTree().Print();
427   }
428   //========================================================================
429
430   void Gimmick::GetSetting(const std::string& name, std::string& value)
431   {
432     value = mSettings->getValue(name);
433   }
434   //========================================================================
435
436   //========================================================================
437
438   void Gimmick::GetAttributes(const std::string& d, 
439                         const std::string& filename, 
440                         const std::vector<std::string>& params, 
441                         std::vector<std::string>& results)
442   {
443           TreeHandler * handler=GetTreeHandler(d);
444           mImageAdder.SetCurrentDatabase(d);
445           mImageAdder.SetTreeHandler(handler);
446           mImageAdder.SetSynchronizer(mSynchronizer);
447           mImageAdder.GetAttributes(params, filename, results);
448   }
449   //========================================================================
450
451   //========================================================================
452   // get attributes values from database  for a given file from database 
453   //========================================================================
454    void Gimmick::GetAttributes(const std::string filename, std::map<std::string, std::string> &i_res, OutputAttr i_attr)
455   {
456            if (i_attr.inside.size() > 0)
457            {
458                    std::map<std::string, std::string> map_attr;
459                    TreeHandler * handler=GetTreeHandler(i_attr.db);
460                    handler->getAllAttributes(filename, map_attr);
461                    if(i_attr.inside.front() == "ALL") // we  take all values
462                    {
463                            std::map<std::string, std::string>::iterator it = map_attr.begin();
464                            for(; it != map_attr.end(); it++)
465                                    i_res[it->first] = it->second;
466                    }
467                    else
468                    {
469                             std::vector<std::string>::iterator it = i_attr.inside.begin();
470                             for(; it != i_attr.inside.end(); it++)
471                                    i_res[(*it)] = map_attr[(*it)];
472                    }
473            }
474   }
475
476
477   //========================================================================
478
479   void Gimmick::UpdateSetting(const std::string& name, const std::string& value)
480   {
481           mSettings->updateSetting(name,value);
482           mSettings->writeSettingsFile();
483   }
484   //========================================================================
485
486   void Gimmick::DeleteDrive(const std::string& drive)
487   {
488         for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
489                                                it!= mTreeHandlerMap.end(); 
490                                                ++it)
491            {
492                    mImageAdder.SetTreeHandler(it->second);
493                    mImageAdder.DeleteDriveFromMainDB(drive);
494            }
495         mImageAdder.SetSynchronizer(mSynchronizer);
496         mImageAdder.DeleteDriveFromOtherDB(drive);
497   }
498
499   //========================================================================
500   void Gimmick::EditField(tree::Node* node, const std::string& d, const std::string& name, const std::string& key, const std::string& val)
501   {
502         TreeHandler * handler=GetTreeHandler(d);
503         mImageAdder.SetCurrentDatabase(d);
504         mImageAdder.SetTreeHandler(handler);
505         mImageAdder.EditField(node,name,key,val);
506   }
507   //========================================================================
508
509   ////////////////////////////////////////////////////////////////////////
510   // add DB from Settings file                                          //
511   // @param : -                                                         //
512   // return : -                                                         //
513   ////////////////////////////////////////////////////////////////////////
514   void Gimmick::addDBSettings()
515   {
516
517          std::string pathSettings = mSettings->getValue(SETTINGS_DBPATH);
518          
519          // split to find all paths
520          std::vector<std::string> paths;
521          std::string separator = ";";
522          std::string::size_type last_pos = pathSettings.find_first_not_of(separator);
523          //find first separator
524          std::string::size_type pos = pathSettings.find_first_of(separator, last_pos);
525          while(std::string::npos != pos || std::string::npos != last_pos)
526          {
527                 paths.push_back(pathSettings.substr(last_pos, pos - last_pos));
528                 last_pos = pathSettings.find_first_not_of(separator, pos);
529                 pos = pathSettings.find_first_of(separator, last_pos);
530          }
531
532          std::vector<std::string>::iterator it_path = paths.begin();
533          for(; it_path != paths.end(); ++it_path)
534          {
535                  pos = it_path->find_last_of("\\");
536                  last_pos = it_path->find_last_of(".");
537                  std::string name = it_path->substr(pos +1, last_pos -pos-1 );
538                  addDB(name, it_path->c_str());
539          }
540   }     
541
542
543 ///////////////////////////////////////////////////////////////////////////////
544 // Fill attributes structure with attributes present in database (inside vector
545 // and not present (outside)
546 ///////////////////////////////////////////////////////////////////////////////
547 void Gimmick::fillVectInfos(std::vector<std::string> i_attr, OutputAttr &infos)
548 {
549         //test if a tag is present in Database descriptor
550         TreeHandler * handler=GetTreeHandler(infos.db);
551         mImageAdder.SetTreeHandler(handler);
552         std::vector<std::string>::const_iterator it = i_attr.begin();
553         for (;it != i_attr.end(); it++)
554         {
555                 if( mImageAdder.isAttributeExist((*it)) != "" ) // in DB
556                 {
557 printf("EED Gimmick::fillVectInfos inside %s\n",(*it).c_str());
558                         infos.inside.push_back((*it));
559                 }
560                 else
561                 {
562                                 infos.outside.push_back((*it)); // Need to scan again the files
563 printf("EED Gimmick::fillVectInfos outside %s\n",(*it).c_str());
564                 }
565         }
566 }
567
568 const std::string Gimmick::getSummary()
569 {
570       const AddProgress& p = GetAddProgress();
571     std::stringstream mess;
572     mess << "Dirs \tscanned\t: " << p.GetNumberScannedDirs()  << "\n";
573     mess << "Files\tscanned\t: " << p.GetNumberScannedFiles() << "\n";
574     mess << "Files\thandled\t: " << p.GetNumberHandledFiles() << "\n\n";
575     mess << "Files\tadded  \t: " << p.GetNumberAddedFiles()   << "\n\n";
576     return mess.str();
577 }
578
579 }