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