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