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