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