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