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