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