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