]> Creatis software - creaImageIO.git/blob - src2/creaImageIOGimmick.cpp
added first version of settings management.
[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.SetTreeHandler(GetTreeHandler(d));
289         mImageAdder.SetTimestampHandler(mTimestampDatabase);
290         mImageAdder.SetSynchronizer(mSynchronizer);
291     mImageAdder.AddFiles(filenames);
292         
293   }
294   //========================================================================
295
296   //========================================================================
297   /// Add a dir to the local database
298   void Gimmick::AddDir(const std::string& d, const std::string& f, 
299                        bool recurse)
300   {
301     GimmickMessage(2,"Adding dir '"<<f<<"' to '"<<d<<"' recurse:"
302                    <<recurse<<std::endl);
303
304         TreeHandler * handler=GetTreeHandler(d);
305     mImageAdder.SetTreeHandler(handler);
306         mImageAdder.SetTimestampHandler(mTimestampDatabase);
307         mImageAdder.SetSynchronizer(mSynchronizer);
308     mImageAdder.AddDirectory(f,recurse);  
309   }
310
311   //========================================================================
312
313   //========================================================================
314   void Gimmick::RemoveFile(const std::string& d, 
315                            tree::Node* node)
316   {
317           mImageAdder.SetSynchronizer(mSynchronizer);
318           mTimestampDatabase->RemoveNode("PATH",node);
319           mImageAdder.RemoveFile(node);
320   }
321   //========================================================================
322
323   //========================================================================
324  
325   std::string Gimmick::Synchronize(bool repair, bool checkAttributes)
326   {
327           TreeHandler * handler=GetTreeHandler("Local database");
328           mImageAdder.SetTreeHandler(handler);
329           mImageAdder.SetTimestampHandler(mTimestampDatabase);
330           mImageAdder.SetSynchronizer(mSynchronizer);
331           return mImageAdder.Synchronize(repair, checkAttributes);
332   }
333
334   //========================================================================
335   /// 
336   void Gimmick::Print(const std::string& d)
337   {
338     GetTreeHandler(d)->GetTree().Print();
339   }
340   //========================================================================
341   /////////////////////////////////////////////////////////////////////////
342   // add DB from Settings file                                                                               //
343   // @param : -                                                                                                                  //
344   // return : -                                                                                                                  //
345   /////////////////////////////////////////////////////////////////////////
346   void Gimmick::addDBSettings()
347   {
348
349          std::string pathSettings = mSettings->getValue(SETTINGS_DBPATH);
350          
351          // split to find all paths
352          std::vector<std::string> paths;
353          std::string separator = ";";
354          std::string::size_type last_pos = pathSettings.find_first_not_of(separator);
355          //find first separator
356          std::string::size_type pos = pathSettings.find_first_of(separator, last_pos);
357          while(std::string::npos != pos || std::string::npos != last_pos)
358          {
359                 paths.push_back(pathSettings.substr(last_pos, pos - last_pos));
360                 last_pos = pathSettings.find_first_not_of(separator, pos);
361                 pos = pathSettings.find_first_of(separator, last_pos);
362          }
363
364          std::vector<std::string>::iterator it_path = paths.begin();
365          for(; it_path != paths.end(); ++it_path)
366          {
367                  pos = it_path->find_last_of("\\");
368                  last_pos = it_path->find_last_of(".");
369                  std::string name = it_path->substr(pos +1, last_pos -pos-1 );
370                  addDB(name, it_path->c_str());
371          }
372
373   }
374         
375 }