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