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