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