]> Creatis software - creaImageIO.git/blob - src2/creaImageIOGimmick.cpp
path correction for MAC OS
[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          // std::string st("C:/Documents and Settings/cervenansky/.gimmick/");
220          //     boost::algorithm::replace_all( st, 
221                 //                     INVALID_FILE_SEPARATOR , 
222                 //                     VALID_FILE_SEPARATOR);
223                 //const boost::filesystem::path mpath(st);
224 //C:\Documents and Settings\cervenansky\.gimmick");
225           //if ( !boost::filesystem::exists( path ) )             return ;
226          //  boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
227          //  for ( boost::filesystem::directory_iterator itr( path );  itr != end_itr;  ++itr )
228          // {
229                 //// If is directory & recurse : do recurse
230                 //      if ( boost::filesystem::is_directory(itr->status()) )
231                 //      return;
232          //  }
233
234           //JCP settings dir 02/10/2009
235           const std::string settingsdirectory = GetUserSettingsDirectory();
236                 //boost::algorithm::replace_all( mUserSettingsDirectory, 
237                                 //       INVALID_FILE_SEPARATOR , 
238                                 //       VALID_FILE_SEPARATOR);
239 ;//("E:\frederic");
240                   //("C:\\Documents and Settings\\cervenansky\\.gimmick\\"); // settingsdirectory );
241                 bool isdir = false;
242            isdir = boost::filesystem::is_directory(settingsdirectory); // settingsdirectory );
243     if (! isdir )
244       {
245         GimmickMessage(1,"Directory '"<<GetUserSettingsDirectory()<<"' "
246                        << "does not exist : creating it"<<std::endl);
247         
248         if ( ! boost::filesystem::create_directory( GetUserSettingsDirectory() ) )
249           {
250             GimmickError("ERROR CREATING '"<<GetUserSettingsDirectory()<<"'");
251           }
252       }
253
254         std::string setDir=GetUserSettingsDirectory();
255         boost::algorithm::replace_all( setDir,
256                                        INVALID_FILE_SEPARATOR , 
257                                        VALID_FILE_SEPARATOR);
258         setDir+="Shared/";
259         boost::filesystem::create_directory( setDir );
260         setDir+="gimmick/";
261         boost::filesystem::create_directory( setDir );
262         setDir+=mLocalDescpName;
263
264         if(!boost::filesystem::is_regular(setDir))
265         {
266                 char name[PATH_MAX];
267 //EED           int err = GetBinaryDirectory(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(__APPLE__)
283                 path+="../../../../shared/gimmick/";
284 #endif 
285
286 #if defined (LINUX)
287                 path+="../shared/gimmick/";
288 #endif  
289                 path+= mLocalDescpName;
290                 std::cout <<"From: " << path   <<std::endl;
291                 std::cout <<"To: "   << setDir <<std::endl;
292                 boost::algorithm::replace_all(  path,
293                                                 INVALID_FILE_SEPARATOR , 
294                                                 VALID_FILE_SEPARATOR);
295                 boost::filesystem::copy_file(path,setDir);
296         }
297   }
298   //========================================================================
299
300
301   //========================================================================
302   /// Sets message level
303   void Gimmick::SetMessageLevel(int l)
304   {
305     SetGimmickMessageLevel(l);
306   }
307   //========================================================================
308
309   //========================================================================
310   /// Sets message level
311   void Gimmick::SetDebugMessageLevel(int l)
312   {
313     SetGimmickDebugMessageLevel(l);
314   }
315   //========================================================================
316
317   //========================================================================
318   /// Returns the tree handler with the given name
319   TreeHandler* Gimmick::GetTreeHandler(const std::string& name) const 
320   {  
321     TreeHandlerMapType::const_iterator i;
322     i = GetTreeHandlerMap().find(name);
323     if ( i == GetTreeHandlerMap().end() )
324       {
325         GimmickError("TreeHandler '"<<name<<"' does not exist");
326       }
327     return i->second;
328   }
329
330   //========================================================================
331   /// Add the files to the tree handler
332   void Gimmick::AddFiles(const std::string& d, 
333                         const std::vector<std::string>& filenames)
334   {
335     GimmickMessage(2,"Adding files to '"<<d<<"'"<<std::endl);
336  
337         mImageAdder.SetCurrentDatabase(d);
338         mImageAdder.SetTreeHandler(GetTreeHandler(d));
339         mImageAdder.SetSynchronizer(mSynchronizer);
340         mImageAdder.AddFiles(filenames);        
341   }
342   //========================================================================
343
344   //========================================================================
345   /// Add a dir to the local database
346   void Gimmick::AddDir(const std::string& d, const std::string& f, 
347                        bool recurse)
348   {
349         GimmickMessage(2,"Adding dir '"<<f<<"' to '"<<d<<"' recurse:"
350                          <<recurse<<std::endl);
351
352         TreeHandler * handler=GetTreeHandler(d);
353         mImageAdder.SetCurrentDatabase(d);
354         mImageAdder.SetTreeHandler(handler);
355         mImageAdder.SetSynchronizer(mSynchronizer);
356         mImageAdder.AddDirectory(f,recurse);  
357   }
358
359   //========================================================================
360
361   //========================================================================
362   void Gimmick::RemoveFile(const std::string& d, 
363                            tree::Node* node)
364   {
365           mImageAdder.SetCurrentDatabase(d);
366           mImageAdder.SetSynchronizer(mSynchronizer);
367           mImageAdder.RemoveFile(node);
368   }
369   //========================================================================
370
371   //========================================================================
372  
373   void Gimmick::CopyFiles(const std::vector<std::string>& filenames, const std::string& d )
374   {
375           TreeHandler * handler=GetTreeHandler(d);
376           mImageAdder.SetCurrentDatabase(d);
377           mImageAdder.SetTreeHandler(handler);
378           mImageAdder.SetSynchronizer(mSynchronizer);
379           mImageAdder.CopyFiles(filenames, mSettings->getValue(SETTINGS_COPY_PATH));
380   }
381
382   //========================================================================
383  
384   std::string Gimmick::Synchronize(const std::string& d, bool repair, bool checkAttributes)
385   {
386           TreeHandler * handler=GetTreeHandler(d);
387           mImageAdder.SetCurrentDatabase(d);
388           mImageAdder.SetTreeHandler(handler);
389           mImageAdder.SetSynchronizer(mSynchronizer);
390           return mImageAdder.Synchronize(repair, checkAttributes);
391   }
392
393   //========================================================================
394   /// 
395   void Gimmick::Print(const std::string& d)
396   {
397     GetTreeHandler(d)->GetTree().Print();
398   }
399   //========================================================================
400
401   void Gimmick::GetSetting(const std::string& name, std::string& value)
402   {
403     value = mSettings->getValue(name);
404   }
405   //========================================================================
406
407   //========================================================================
408
409   void Gimmick::GetAttributes(const std::string& d, 
410                         const std::string& filename, 
411                         const std::vector<std::string>& params, 
412                         std::vector<std::string>& results)
413   {
414           TreeHandler * handler=GetTreeHandler(d);
415           mImageAdder.SetCurrentDatabase(d);
416           mImageAdder.SetTreeHandler(handler);
417           mImageAdder.SetSynchronizer(mSynchronizer);
418           mImageAdder.GetAttributes(params, filename, results);
419   }
420   //========================================================================
421
422   //========================================================================
423
424   void Gimmick::UpdateSetting(const std::string& name, const std::string& value)
425   {
426           mSettings->updateSetting(name,value);
427           mSettings->writeSettingsFile();
428   }
429   //========================================================================
430
431   void Gimmick::DeleteDrive(const std::string& drive)
432   {
433         for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
434                                                it!= mTreeHandlerMap.end(); 
435                                                ++it)
436            {
437                    mImageAdder.SetTreeHandler(it->second);
438                    mImageAdder.DeleteDriveFromMainDB(drive);
439            }
440         mImageAdder.SetSynchronizer(mSynchronizer);
441         mImageAdder.DeleteDriveFromOtherDB(drive);
442   }
443
444   //========================================================================
445   void Gimmick::EditField(tree::Node* node, const std::string& d, const std::string& name, const std::string& key, const std::string& val)
446   {
447         TreeHandler * handler=GetTreeHandler(d);
448         mImageAdder.SetCurrentDatabase(d);
449         mImageAdder.SetTreeHandler(handler);
450         mImageAdder.EditField(node,name,key,val);
451   }
452   //========================================================================
453
454   ////////////////////////////////////////////////////////////////////////
455   // add DB from Settings file                                          //
456   // @param : -                                                         //
457   // return : -                                                         //
458   ////////////////////////////////////////////////////////////////////////
459   void Gimmick::addDBSettings()
460   {
461
462          std::string pathSettings = mSettings->getValue(SETTINGS_DBPATH);
463          
464          // split to find all paths
465          std::vector<std::string> paths;
466          std::string separator = ";";
467          std::string::size_type last_pos = pathSettings.find_first_not_of(separator);
468          //find first separator
469          std::string::size_type pos = pathSettings.find_first_of(separator, last_pos);
470          while(std::string::npos != pos || std::string::npos != last_pos)
471          {
472                 paths.push_back(pathSettings.substr(last_pos, pos - last_pos));
473                 last_pos = pathSettings.find_first_not_of(separator, pos);
474                 pos = pathSettings.find_first_of(separator, last_pos);
475          }
476
477          std::vector<std::string>::iterator it_path = paths.begin();
478          for(; it_path != paths.end(); ++it_path)
479          {
480                  pos = it_path->find_last_of("\\");
481                  last_pos = it_path->find_last_of(".");
482                  std::string name = it_path->substr(pos +1, last_pos -pos-1 );
483                  addDB(name, it_path->c_str());
484          }
485   }     
486 }