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