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