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