]> Creatis software - creaImageIO.git/blob - src2/creaImageIOGimmick.cpp
af7f7010c1dc9276d32b0de3647f10995ab52d8a
[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         mLocalDatabase = createDB(i_nameDB, mCurrentDirectory + "\\.gimmick\\localdatabase_Descriptor.txt", dbpath);
59     // Add it to the TreeHandlerMap
60     mTreeHandlerMap[i_nameDB] = mLocalDatabase;
61     
62         //Add additional DB from user Settings
63         addDBSettings();
64
65         // Creates files and directories database
66     mTimestampDatabase = new TimestampDatabaseHandler(GetTimestampDatabasePath());
67     // Create or open local database
68     if (! boost::filesystem::exists( GetTimestampDatabasePath() ) )
69       {
70         std::string mess = "Timestamp database '";
71         mess += GetTimestampDatabasePath();
72         mess += "' does not exist : creating it";
73         GimmickMessage(1,mess<<std::endl);
74         
75         if ( ! mTimestampDatabase->Create() )
76           {
77             GimmickError("ERROR CREATING '"<<GetTimestampDatabasePath()<<"'");
78           }
79         
80      }
81     else 
82       {
83         /// Open and test it
84         GimmickMessage(1,"Opening Timestamp database '"
85                        <<GetTimestampDatabasePath()<<"' "
86                        <<std::endl);
87         if ( ! mTimestampDatabase->Open() )
88           {
89             GimmickError("ERROR OPENING '"<<GetTimestampDatabasePath()<<"'");
90           }
91         
92       }
93
94   }
95
96    ///////////////////////////////////////////////////////////////////////
97    // add DB to TreeHandler Map                                                                                 //
98    // @param i_name : DB name                                                                               //
99    // @param i_location : DB location                                                               //
100    // return : -                                                                                                                //
101   ///////////////////////////////////////////////////////////////////////
102         void Gimmick::addDB(const std::string &i_name, 
103                             const std::string &i_location)
104         {
105                 if(mTreeHandlerMap.find(i_name) == mTreeHandlerMap.end())
106                 {
107                         mTreeHandlerMap[i_name] = new SQLiteTreeHandler(i_location);
108                         mTreeHandlerMap[i_name]->Open(true);
109                         mSettings->addDB(i_location);
110                 }
111         }
112
113  
114   ///////////////////////////////////////////////////////////////////////////
115   // create a DB from a attributes descriptor file for medical images      //
116   // @param i_name : DB name                                                                                       //
117   // @param i_locDesc : location of descriptor file                                                //
118   // @param i_locDB : location of DB                                                                       //
119   // return : the SQLiteTreeHandler object on DB                                                   //
120         /////////////////////////////////////////////////////////////////////////
121         SQLiteTreeHandler *Gimmick::createDB(const std::string &i_name,
122                                              const std::string &i_locDesc,
123                                              const std::string &i_locDB)
124   {
125       SQLiteTreeHandler *sqlTreeH = new SQLiteTreeHandler(i_locDB);
126     // Create or open local database
127     if (! boost::filesystem::exists(i_locDB) )
128      {
129          std::string mess = "Local database '";
130          mess += i_locDB;
131          mess += "' does not exist : creating it";
132          GimmickMessage(1,mess<<std::endl);
133          
134                  // CREATING DB STRUCTURE
135          sqlTreeH->GetTree().GetDescriptor().createDescriptorfromFile(i_locDesc);
136          if ( ! sqlTreeH->Create(true) )
137                  {
138                         GimmickError("ERROR CREATING '"<<i_locDB<<"'");
139          }
140          sqlTreeH->SetAttribute(0,"Name",i_name);
141          }
142          else 
143          {
144                 /// Open and test it
145                 GimmickMessage(1,"Opening local database '" <<i_locDB<< "' " << std::endl);
146         if ( !sqlTreeH->Open(true) )
147                 {
148                         GimmickError("ERROR OPENING '"<<i_locDB<<"'");
149                 }
150       }
151          return sqlTreeH;
152   }
153
154
155   //==============================================================
156   void Gimmick::Finalize()
157   {
158          
159           // delete SQLiteTreeHandler Object
160            for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
161            it!= mTreeHandlerMap.end(); ++it)
162            {
163                    delete it->second;
164            }
165         delete mTimestampDatabase;
166   }
167   //==============================================================
168
169   //================================================================
170   // file separator
171 #if defined(_WIN32)
172 #define VALID_FILE_SEPARATOR "\\"
173 #define INVALID_FILE_SEPARATOR "/"
174 #else
175 #define INVALID_FILE_SEPARATOR "\\"
176 #define VALID_FILE_SEPARATOR "/"
177 #endif
178   //================================================================
179
180   //================================================================
181   const std::string& Gimmick::GetHomeDirectory()
182   {
183     if (mHomeDirectory.size()==0) 
184       {
185 #if defined(__GNUC__)
186         mHomeDirectory = getenv("HOME");
187 #elif defined(_WIN32)
188         mHomeDirectory = getenv("USERPROFILE");
189 #endif
190       }
191     return mHomeDirectory;
192   }
193   //================================================================
194   const std::string& Gimmick::GetUserSettingsDirectory()
195   {
196     if (mUserSettingsDirectory.size()==0) 
197       {
198         mUserSettingsDirectory = GetHomeDirectory();
199         mUserSettingsDirectory += "/.gimmick/";
200         boost::algorithm::replace_all( mUserSettingsDirectory, 
201                                        INVALID_FILE_SEPARATOR , 
202                                        VALID_FILE_SEPARATOR);
203       }
204     return mUserSettingsDirectory;
205   }
206   //================================================================
207
208   //================================================================
209   int Gimmick::GetBinaryDirectory(char *pname, size_t pathsize)
210   {
211
212         #ifdef LINUX    
213                 /* Oddly, the readlink(2) man page says no NULL is appended. */
214                 /* So you have to do it yourself, based on the return value: */
215                 pathsize --; /* Preserve a space to add the trailing NULL */
216                 long result = readlink("/proc/self/exe", pname, pathsize);
217                 if (result > 0)
218                 {
219                         pname[result] = 0; /* add the #@!%ing NULL */
220                         
221                         if ((access(pname, 0) == 0))
222                                 return 0; /* file exists, return OK */
223                         /*else name doesn't seem to exist, return FAIL (falls
224                         through) */
225                 }
226         #endif /* LINUX */
227             
228         #ifdef WIN32
229                 long result = GetModuleFileName(NULL, pname, pathsize);
230                 if (result > 0)
231                 {
232                         /* fix up the dir slashes... */
233                         int len = strlen(pname);
234                         int idx;
235                         for (idx = 0; idx < len; idx++)
236                         {
237                                 if (pname[idx] == '\\') pname[idx] = '/';
238                         }
239                         
240                         for (idx = len-1; idx >=0 ; idx--)
241                         {
242                                 if (pname[idx] == '/')
243                                 { 
244                                         pname[idx+1] = '\0';
245                                         idx = -1;
246                                 }
247                         }
248                         
249                         if ((access(pname, 0) == 0))
250                                 return 0; /* file exists, return OK */
251                         /*else name doesn't seem to exist, return FAIL (falls
252                         through) */
253                 }
254         #endif /* WIN32 */
255             
256         #ifdef SOLARIS
257                 char *p = getexecname();
258                 if (p)
259                 {
260                         /* According to the Sun manpages, getexecname will
261                         "normally" return an */
262                         /* absolute path - BUT might not... AND that IF it is not,
263                         pre-pending */
264                         /* getcwd() will "usually" be the correct thing... Urgh!
265                         */
266                         
267                         /* check pathname is absolute (begins with a / ???) */
268                         if (p[0] == '/') /* assume this means we have an
269                         absolute path */
270                         {
271                                 strncpy(pname, p, pathsize);
272                                 if ((access(pname, 0) == 0))
273                                         return 0; /* file exists, return OK */
274                         }
275                         else /* if not, prepend getcwd() then check if file
276                         exists */
277                         {
278                                 getcwd(pname, pathsize);
279                                 long result = strlen(pname);
280                                 strncat(pname, "/", (pathsize - result));
281                                 result ++;
282                                 strncat(pname, p, (pathsize - result));
283                                 
284                                 if ((access(pname, 0) == 0))
285                                         return 0; /* file exists, return OK */
286                                 /*else name doesn't seem to exist, return FAIL
287                                 (falls through) */
288                         }
289                 }
290         #endif /* SOLARIS */
291             
292         #ifdef MACOSX /* assume this is OSX */
293                 /*
294                 from http://www.hmug.org/man/3/NSModule.html
295                  
296                 extern int _NSGetExecutablePath(char *buf, unsigned long
297                 *bufsize);
298                  
299                 _NSGetExecutablePath  copies  the  path  of the executable
300                 into the buffer and returns 0 if the path was successfully
301                 copied  in the provided buffer. If the buffer is not large
302                 enough, -1 is returned and the  expected  buffer  size  is
303                 copied  in  *bufsize.  Note that _NSGetExecutablePath will
304                 return "a path" to the executable not a "real path" to the
305                 executable.  That  is  the path may be a symbolic link and
306                 not the real file. And with  deep  directories  the  total
307                 bufsize needed could be more than MAXPATHLEN.
308                 */
309                 
310                 int status = -1;
311                 char *given_path = (char*)malloc(MAXPATHLEN * 2);
312                 if (!given_path) return status;
313             
314                 uint32_t npathsize = MAXPATHLEN * 2;
315                 long result = _NSGetExecutablePath(given_path, &npathsize);
316                 if (result == 0)
317                 { /* OK, we got something - now try and resolve the real path...
318                 */
319                         if (realpath(given_path, pname) != NULL)
320                         {
321                                 if ((access(pname, 0) == 0))
322                                         status = 0; /* file exists, return OK */
323                         }
324                 }
325                 free (given_path);
326                 return status;
327         #endif /* MACOSX */
328             
329                 return -1; /* Path Lookup Failed */
330   }
331
332   //================================================================
333   const std::string& Gimmick::GetLocalDatabasePath()
334   {
335     if (mLocalDatabasePath.size()==0) 
336       {
337         mLocalDatabasePath = GetUserSettingsDirectory();
338         mLocalDatabasePath += "local_database.sqlite3";
339         boost::algorithm::replace_all( mLocalDatabasePath,
340                                        INVALID_FILE_SEPARATOR , 
341                                        VALID_FILE_SEPARATOR);
342       }
343     return mLocalDatabasePath;    
344   }
345
346   //================================================================
347
348   //================================================================
349   const std::string& Gimmick::GetTimestampDatabasePath()
350   {
351     if (mTimestampDatabasePath.size()==0) 
352       {
353         mTimestampDatabasePath = GetUserSettingsDirectory();
354         mTimestampDatabasePath += "timestamp_database.sqlite3";
355         boost::algorithm::replace_all( mTimestampDatabasePath,
356                                        INVALID_FILE_SEPARATOR , 
357                                        VALID_FILE_SEPARATOR);
358       }
359     return mTimestampDatabasePath;    
360   }
361   //========================================================================
362
363   //========================================================================
364   void Gimmick::CreateUserSettingsDirectory()
365   {
366     if (! boost::filesystem::is_directory( GetUserSettingsDirectory() ) )
367       {
368         GimmickMessage(1,"Directory '"<<GetUserSettingsDirectory()<<"' "
369                        << "does not exist : creating it"<<std::endl);
370         
371         if ( ! boost::filesystem::create_directory( GetUserSettingsDirectory() ) )
372           {
373             GimmickError("ERROR CREATING '"<<GetUserSettingsDirectory()<<"'");
374           }
375       }
376
377         std::string setDir=GetUserSettingsDirectory();
378         boost::algorithm::replace_all( setDir,
379                                        VALID_FILE_SEPARATOR , 
380                                        INVALID_FILE_SEPARATOR);
381         setDir+="localdatabase_Descriptor.txt";
382         if(!boost::filesystem::is_regular_file(setDir))
383         {
384                 char name[PATH_MAX];
385                 int err = GetBinaryDirectory(name, PATH_MAX);
386                 std::string path=name;
387                 path=path.substr(0,path.size()-1);
388                 path=path.substr(0,path.find_last_of("/"));
389                 path+="/data/localdatabase_Descriptor.txt";
390                 boost::algorithm::replace_all( path,
391                                                 VALID_FILE_SEPARATOR , 
392                                                 INVALID_FILE_SEPARATOR);
393                 boost::filesystem::copy_file(path,setDir);
394         }
395   }
396   //========================================================================
397
398
399   //========================================================================
400   /// Sets message level
401   void Gimmick::SetMessageLevel(int l)
402   {
403     SetGimmickMessageLevel(l);
404   }
405   //========================================================================
406
407   //========================================================================
408   /// Sets message level
409   void Gimmick::SetDebugMessageLevel(int l)
410   {
411     SetGimmickDebugMessageLevel(l);
412   }
413   //========================================================================
414
415   //========================================================================
416   /// Returns the tree handler with the given name
417   TreeHandler* Gimmick::GetTreeHandler(const std::string& name) const 
418   {  
419     TreeHandlerMapType::const_iterator i;
420     i = GetTreeHandlerMap().find(name);
421     if ( i == GetTreeHandlerMap().end() )
422       {
423         GimmickError("TreeHandler '"<<name<<"' does not exist");
424       }
425     return i->second;
426   }
427
428   //========================================================================
429   ///Returns the timestamp database handler
430   TimestampDatabaseHandler* Gimmick::GetTimestampDatabase() const 
431   {  
432     return mTimestampDatabase;
433   }
434
435
436   //========================================================================
437   /// Add the files to the tree handler
438   void Gimmick::AddFiles(const std::string& d, 
439                         const std::vector<std::string>& filenames)
440   {
441     GimmickMessage(2,"Adding files to '"<<d<<"'"<<std::endl);
442  
443         mImageAdder.SetCurrentDatabase(d);
444     mImageAdder.SetTreeHandler(GetTreeHandler(d));
445         mImageAdder.SetTimestampHandler(mTimestampDatabase);
446         mImageAdder.SetSynchronizer(mSynchronizer);
447     mImageAdder.AddFiles(filenames);
448         
449   }
450   //========================================================================
451
452   //========================================================================
453   /// Add a dir to the local database
454   void Gimmick::AddDir(const std::string& d, const std::string& f, 
455                        bool recurse)
456   {
457     GimmickMessage(2,"Adding dir '"<<f<<"' to '"<<d<<"' recurse:"
458                    <<recurse<<std::endl);
459
460         TreeHandler * handler=GetTreeHandler(d);
461         mImageAdder.SetCurrentDatabase(d);
462     mImageAdder.SetTreeHandler(handler);
463         mImageAdder.SetTimestampHandler(mTimestampDatabase);
464         mImageAdder.SetSynchronizer(mSynchronizer);
465     mImageAdder.AddDirectory(f,recurse);  
466   }
467
468   //========================================================================
469
470   //========================================================================
471   void Gimmick::RemoveFile(const std::string& d, 
472                            tree::Node* node)
473   {
474           mImageAdder.SetCurrentDatabase(d);
475           mImageAdder.SetSynchronizer(mSynchronizer);
476           mTimestampDatabase->RemoveNode("PATH",node,d);
477           mImageAdder.RemoveFile(node);
478   }
479   //========================================================================
480
481   //========================================================================
482  
483   void Gimmick::CopyFiles(const std::vector<std::string>& filenames, const std::string& d )
484   {
485           TreeHandler * handler=GetTreeHandler(d);
486           mImageAdder.SetCurrentDatabase(d);
487           mImageAdder.SetTreeHandler(handler);
488           mImageAdder.SetTimestampHandler(mTimestampDatabase);
489           mImageAdder.SetSynchronizer(mSynchronizer);
490           mImageAdder.CopyFiles(filenames, mSettings->getValue(SETTINGS_COPY_PATH));
491   }
492
493   //========================================================================
494  
495   std::string Gimmick::Synchronize(const std::string& d, bool repair, bool checkAttributes)
496   {
497           TreeHandler * handler=GetTreeHandler(d);
498           mImageAdder.SetCurrentDatabase(d);
499           mImageAdder.SetTreeHandler(handler);
500           mImageAdder.SetTimestampHandler(mTimestampDatabase);
501           mImageAdder.SetSynchronizer(mSynchronizer);
502           return mImageAdder.Synchronize(repair, checkAttributes);
503   }
504
505   //========================================================================
506   /// 
507   void Gimmick::Print(const std::string& d)
508   {
509     GetTreeHandler(d)->GetTree().Print();
510   }
511   //========================================================================
512
513   void Gimmick::GetSetting(const std::string& name, std::string& value)
514   {
515           value = mSettings->getValue(name);
516   }
517   //========================================================================
518
519   //========================================================================
520
521   void Gimmick::UpdateSetting(const std::string& name, const std::string& value)
522   {
523           mSettings->updateSetting(name,value);
524           mSettings->writeSettingsFile();
525   }
526   //========================================================================
527
528   void Gimmick::DeleteDrive(const std::string& drive)
529   {
530           for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
531            it!= mTreeHandlerMap.end(); ++it)
532            {
533                    mImageAdder.SetTreeHandler(it->second);
534                    mImageAdder.DeleteDriveFromMainDB(drive);
535            }
536           mImageAdder.SetTimestampHandler(mTimestampDatabase);
537           mImageAdder.SetSynchronizer(mSynchronizer);
538           mImageAdder.DeleteDriveFromOtherDB(drive);
539   }
540
541   //========================================================================
542   void Gimmick::EditField(tree::Node* node, const std::string& d, const std::string& name, const std::string& key, const std::string& val)
543   {
544           TreeHandler * handler=GetTreeHandler(d);
545           mImageAdder.SetCurrentDatabase(d);
546           mImageAdder.SetTreeHandler(handler);
547           mImageAdder.EditField(node,name,key,val);
548   }
549   //========================================================================
550
551
552   /////////////////////////////////////////////////////////////////////////
553   // add DB from Settings file                                                                               //
554   // @param : -                                                                                                                  //
555   // return : -                                                                                                                  //
556   /////////////////////////////////////////////////////////////////////////
557   void Gimmick::addDBSettings()
558   {
559
560          std::string pathSettings = mSettings->getValue(SETTINGS_DBPATH);
561          
562          // split to find all paths
563          std::vector<std::string> paths;
564          std::string separator = ";";
565          std::string::size_type last_pos = pathSettings.find_first_not_of(separator);
566          //find first separator
567          std::string::size_type pos = pathSettings.find_first_of(separator, last_pos);
568          while(std::string::npos != pos || std::string::npos != last_pos)
569          {
570                 paths.push_back(pathSettings.substr(last_pos, pos - last_pos));
571                 last_pos = pathSettings.find_first_not_of(separator, pos);
572                 pos = pathSettings.find_first_of(separator, last_pos);
573          }
574
575          std::vector<std::string>::iterator it_path = paths.begin();
576          for(; it_path != paths.end(); ++it_path)
577          {
578                  pos = it_path->find_last_of("\\");
579                  last_pos = it_path->find_last_of(".");
580                  std::string name = it_path->substr(pos +1, last_pos -pos-1 );
581                  addDB(name, it_path->c_str());
582          }
583
584   }
585         
586 }