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