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