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