]> Creatis software - creaImageIO.git/blob - src2/creaImageIOGimmick.cpp
Try to make it work on Windows, as well.
[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(); ++it)
135            {
136                    delete it->second;
137            }
138   }
139   //==============================================================
140
141   //================================================================
142   // file separator
143 #if defined(_WIN32)
144 #define VALID_FILE_SEPARATOR "\\"
145 #define INVALID_FILE_SEPARATOR "/"
146 #else
147 #define INVALID_FILE_SEPARATOR "\\"
148 #define VALID_FILE_SEPARATOR "/"
149 #endif
150   //================================================================
151
152   //================================================================
153   const std::string& Gimmick::GetHomeDirectory()
154   {
155     if (mHomeDirectory.size()==0) 
156       {
157 #if defined(__GNUC__)
158         mHomeDirectory = getenv("HOME");
159 #elif defined(_WIN32)
160         mHomeDirectory = getenv("USERPROFILE");
161 #endif
162       }
163     return mHomeDirectory;
164   }
165   //================================================================
166   const std::string& Gimmick::GetUserSettingsDirectory()
167   {
168     if (mUserSettingsDirectory.size()==0) 
169       {
170         mUserSettingsDirectory = GetHomeDirectory();
171         mUserSettingsDirectory += "/.gimmick/";
172         boost::algorithm::replace_all( mUserSettingsDirectory, 
173                                        INVALID_FILE_SEPARATOR , 
174                                        VALID_FILE_SEPARATOR);
175       }
176     return mUserSettingsDirectory;
177   }
178   //================================================================
179
180
181   //================================================================
182   const std::string& Gimmick::GetLocalDatabasePath()
183   {
184     if (mLocalDatabasePath.size()==0) 
185       {
186         mLocalDatabasePath = GetUserSettingsDirectory();
187         mLocalDatabasePath += "Shared/gimmick/local_database.sqlite3";
188         boost::algorithm::replace_all( mLocalDatabasePath,
189                                        INVALID_FILE_SEPARATOR , 
190                                        VALID_FILE_SEPARATOR);
191       }
192     return mLocalDatabasePath;    
193   }
194
195   //========================================================================
196
197   //========================================================================
198   void Gimmick::CreateUserSettingsDirectory()
199   {
200     if (! boost::filesystem::is_directory( GetUserSettingsDirectory() ) )
201       {
202         GimmickMessage(1,"Directory '"<<GetUserSettingsDirectory()<<"' "
203                        << "does not exist : creating it"<<std::endl);
204         
205         if ( ! boost::filesystem::create_directory( GetUserSettingsDirectory() ) )
206           {
207             GimmickError("ERROR CREATING '"<<GetUserSettingsDirectory()<<"'");
208           }
209       }
210
211         std::string setDir=GetUserSettingsDirectory();
212         boost::algorithm::replace_all( setDir,
213                                        INVALID_FILE_SEPARATOR , 
214                                        VALID_FILE_SEPARATOR);
215         setDir+="Shared/";
216         boost::filesystem::create_directory( setDir );
217         setDir+="gimmick/";
218         boost::filesystem::create_directory( setDir );
219         setDir+="localdatabase_Descriptor.dscp";
220
221         if(!boost::filesystem::is_regular(setDir))
222         {
223                 char name[PATH_MAX];
224 //EED           int err = GetBinaryDirectory(name, PATH_MAX);
225                 crea::System::GetAppPath(name,PATH_MAX);
226                 std::cout<<name<<std::endl;
227                 
228                 std::string path=name;
229                 path=path.substr(0,path.size()-1);
230                 path=path.substr(0,path.find_last_of("/"));
231                 //Creating directories
232
233 // The following stuff works on Linux, NOT CHECKED on Windows // JPR
234                 
235 #if defined(_WIN32)             
236                 path+="/bin/Shared/gimmick/localdatabase_Descriptor.dscp";
237 #else           
238                 path+="/Shared/gimmick/localdatabase_Descriptor.dscp";
239 #endif          
240                 std::cout <<"From: " << path   <<std::endl;
241                 std::cout <<"To: "   << setDir <<std::endl;
242                 boost::algorithm::replace_all(  path,
243                                                 INVALID_FILE_SEPARATOR , 
244                                                 VALID_FILE_SEPARATOR);
245                 boost::filesystem::copy_file(path,setDir);
246         }
247   }
248   //========================================================================
249
250
251   //========================================================================
252   /// Sets message level
253   void Gimmick::SetMessageLevel(int l)
254   {
255     SetGimmickMessageLevel(l);
256   }
257   //========================================================================
258
259   //========================================================================
260   /// Sets message level
261   void Gimmick::SetDebugMessageLevel(int l)
262   {
263     SetGimmickDebugMessageLevel(l);
264   }
265   //========================================================================
266
267   //========================================================================
268   /// Returns the tree handler with the given name
269   TreeHandler* Gimmick::GetTreeHandler(const std::string& name) const 
270   {  
271     TreeHandlerMapType::const_iterator i;
272     i = GetTreeHandlerMap().find(name);
273     if ( i == GetTreeHandlerMap().end() )
274       {
275         GimmickError("TreeHandler '"<<name<<"' does not exist");
276       }
277     return i->second;
278   }
279
280   //========================================================================
281   /// Add the files to the tree handler
282   void Gimmick::AddFiles(const std::string& d, 
283                         const std::vector<std::string>& filenames)
284   {
285     GimmickMessage(2,"Adding files to '"<<d<<"'"<<std::endl);
286  
287         mImageAdder.SetCurrentDatabase(d);
288     mImageAdder.SetTreeHandler(GetTreeHandler(d));
289         mImageAdder.SetSynchronizer(mSynchronizer);
290         mImageAdder.AddFiles(filenames);
291         
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(); ++it)
386            {
387                    mImageAdder.SetTreeHandler(it->second);
388                    mImageAdder.DeleteDriveFromMainDB(drive);
389            }
390           mImageAdder.SetSynchronizer(mSynchronizer);
391           mImageAdder.DeleteDriveFromOtherDB(drive);
392   }
393
394   //========================================================================
395   void Gimmick::EditField(tree::Node* node, const std::string& d, const std::string& name, const std::string& key, const std::string& val)
396   {
397           TreeHandler * handler=GetTreeHandler(d);
398           mImageAdder.SetCurrentDatabase(d);
399           mImageAdder.SetTreeHandler(handler);
400           mImageAdder.EditField(node,name,key,val);
401   }
402   //========================================================================
403
404   ////////////////////////////////////////////////////////////////////////
405   // add DB from Settings file                                          //
406   // @param : -                                                         //
407   // return : -                                                         //
408   ////////////////////////////////////////////////////////////////////////
409   void Gimmick::addDBSettings()
410   {
411
412          std::string pathSettings = mSettings->getValue(SETTINGS_DBPATH);
413          
414          // split to find all paths
415          std::vector<std::string> paths;
416          std::string separator = ";";
417          std::string::size_type last_pos = pathSettings.find_first_not_of(separator);
418          //find first separator
419          std::string::size_type pos = pathSettings.find_first_of(separator, last_pos);
420          while(std::string::npos != pos || std::string::npos != last_pos)
421          {
422                 paths.push_back(pathSettings.substr(last_pos, pos - last_pos));
423                 last_pos = pathSettings.find_first_not_of(separator, pos);
424                 pos = pathSettings.find_first_of(separator, last_pos);
425          }
426
427          std::vector<std::string>::iterator it_path = paths.begin();
428          for(; it_path != paths.end(); ++it_path)
429          {
430                  pos = it_path->find_last_of("\\");
431                  last_pos = it_path->find_last_of(".");
432                  std::string name = it_path->substr(pos +1, last_pos -pos-1 );
433                  addDB(name, it_path->c_str());
434          }
435   }     
436 }