2 # ---------------------------------------------------------------------
4 # Copyright (c) CREATIS (Centre de Recherche en Acquisition et Traitement de l'Image
6 # Authors : Eduardo Davila, Frederic Cervenansky, Claire Mouton
7 # Previous Authors : Laurent Guigues, Jean-Pierre Roux
8 # CreaTools website : www.creatis.insa-lyon.fr/site/fr/creatools_accueil
10 # This software is governed by the CeCILL-B license under French law and
11 # abiding by the rules of distribution of free software. You can use,
12 # modify and/ or redistribute the software under the terms of the CeCILL-B
13 # license as circulated by CEA, CNRS and INRIA at the following URL
14 # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
15 # or in the file LICENSE.txt.
17 # As a counterpart to the access to the source code and rights to copy,
18 # modify and redistribute granted by the license, users are provided only
19 # with a limited warranty and the software's author, the holder of the
20 # economic rights, and the successive licensors have only limited
23 # The fact that you are presently reading this means that you have had
24 # knowledge of the CeCILL-B license and that you accept its terms.
25 # ------------------------------------------------------------------------
28 #include <creaImageIOGimmick.h>
30 #include <boost/filesystem.hpp>
31 #include <boost/algorithm/string.hpp>
34 #ifndef PATH_MAX // If not defined yet : do it
35 # define PATH_MAX 2048
37 #include <creaImageIOGimmick.h>
40 #pragma warning(disable: 4996)
50 //==============================================================
54 RegisterGimmickMessageTypes();
57 mLocalDescpName = "localdatabase_Descriptor.dscp";
58 mLocalDBName = "Local database";
60 //==============================================================
63 //==============================================================
68 mSettings->writeSettingsFile();
71 if(mSynchronizer!=NULL)
76 //==============================================================
78 //==============================================================
79 void Gimmick::Initialize(const std::string i_namedescp, const std::string i_namedb)
81 mLocalDescpName = i_namedescp;
82 mLocalDBName = i_namedb;
86 //==============================================================
87 void Gimmick::Initialize()
89 std::string i_nameDB = mLocalDBName;
90 // Create the UserSettings dir if does not exist
91 CreateUserSettingsDirectory();
92 // Sets the current directory to the home dir
93 mCurrentDirectory = GetHomeDirectory();
94 mSynchronizer= new Synchronizer( GetUserSettingsDirectory()+"share/creaImageIO/" );
95 mSettings = new Settings(mCurrentDirectory);
96 std::string dbpath = GetLocalDatabasePath();
97 // Create or open local database
98 std::string dpath= mCurrentDirectory + "/.creaImageIO/share/creaImageIO/" + mLocalDescpName;
99 boost::algorithm::replace_all( dpath,
100 INVALID_FILE_SEPARATOR ,
101 VALID_FILE_SEPARATOR);
102 mLocalDatabase = createDB(i_nameDB, dpath, dbpath);
103 // Add it to the TreeHandlerMap
104 mTreeHandlerMap[i_nameDB] = mLocalDatabase;
105 //Add additional DB from user Settings
109 ///////////////////////////////////////////////////////////////////////
110 // add DB to TreeHandler Map //
111 // @param i_name : DB name //
112 // @param i_location : DB location //
114 ////////////////////////////////////////////////////////////////////////
115 void Gimmick::addDB(const std::string &i_name,
116 const std::string &i_location)
118 if(mTreeHandlerMap.find(i_name) == mTreeHandlerMap.end())
120 mTreeHandlerMap[i_name] = new SQLiteTreeHandler(i_location);
121 mTreeHandlerMap[i_name]->Open(true);
122 mSettings->addDB(i_location);
126 ///////////////////////////////////////////////////////////////////////////
127 // create a DB from a attributes descriptor file for medical images //
128 // @param i_name : DB name //
129 // @param i_locDesc : location of descriptor file //
130 // @param i_locDB : location of DB //
131 // return : the SQLiteTreeHandler object on DB //
132 /////////////////////////////////////////////////////////////////////////
133 SQLiteTreeHandler* Gimmick::createDB(const std::string &i_name,
134 const std::string &i_locDesc,
135 const std::string &i_locDB)
137 SQLiteTreeHandler* sqlTreeH( new SQLiteTreeHandler(i_locDB) );
138 // Create or open local database
139 if (! boost::filesystem::exists(i_locDB) )
141 std::string mess = "Local database '";
143 mess += "' does not exist : creating it";
144 GimmickMessage(1,mess<<std::endl);
146 // CREATING DB STRUCTURE
147 sqlTreeH->GetTree().GetDescriptor().createDescriptorfromFile(i_locDesc);
148 if ( ! sqlTreeH->Create(true) )
150 GimmickError("ERROR CREATING '"<<i_locDB<<"'");
152 sqlTreeH->SetAttribute(0,"Name",i_name);
158 GimmickDebugMessage(1,"Opening local database '" <<i_locDB<< "' " << std::endl);
159 if ( !sqlTreeH->Open(true) )
161 GimmickError("ERROR OPENING '"<<i_locDB<<"'");
167 //==============================================================
168 void Gimmick::Finalize()
170 if(mTreeHandlerMap.size() >0)
172 // delete SQLiteTreeHandler Object
173 for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
174 it!= mTreeHandlerMap.end();
181 //==============================================================
183 //================================================================
186 #define VALID_FILE_SEPARATOR "\\"
187 #define INVALID_FILE_SEPARATOR "/"
189 #define INVALID_FILE_SEPARATOR "\\"
190 #define VALID_FILE_SEPARATOR "/"
192 //================================================================
194 //================================================================
195 const std::string& Gimmick::GetHomeDirectory()
197 if (mHomeDirectory.size()==0)
200 mHomeDirectory = getenv("USERPROFILE");
201 #elif defined(__GNUC__)
202 mHomeDirectory = getenv("HOME");
205 return mHomeDirectory;
207 //================================================================
208 const std::string& Gimmick::GetUserSettingsDirectory()
210 if (mUserSettingsDirectory.size()==0)
212 mUserSettingsDirectory = GetHomeDirectory();
213 mUserSettingsDirectory += "/.creaImageIO/";
214 boost::algorithm::replace_all( mUserSettingsDirectory,
215 INVALID_FILE_SEPARATOR ,
216 VALID_FILE_SEPARATOR);
218 return mUserSettingsDirectory;
220 //================================================================
223 //================================================================
224 const std::string& Gimmick::GetLocalDatabasePath()
226 if (mLocalDatabasePath.size()==0)
228 mLocalDatabasePath = GetUserSettingsDirectory();
229 mLocalDatabasePath += "share/creaImageIO/";
230 mLocalDatabasePath += mLocalDBName;
231 mLocalDatabasePath +=".sqlite3";
232 boost::algorithm::replace_all( mLocalDatabasePath,
233 INVALID_FILE_SEPARATOR ,
234 VALID_FILE_SEPARATOR);
236 return mLocalDatabasePath;
239 //========================================================================
241 //========================================================================
242 void Gimmick::CreateUserSettingsDirectory()
245 // std::string st("C:/Documents and Settings/cervenansky/.gimmick/");
246 // boost::algorithm::replace_all( st,
247 // INVALID_FILE_SEPARATOR ,
248 // VALID_FILE_SEPARATOR);
249 //const boost::filesystem::path mpath(st);
250 //C:\Documents and Settings\cervenansky\.gimmick");
251 //if ( !boost::filesystem::exists( path ) ) return ;
252 // boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
253 // for ( boost::filesystem::directory_iterator itr( path ); itr != end_itr; ++itr )
255 //// If is directory & recurse : do recurse
256 // if ( boost::filesystem::is_directory(itr->status()) )
260 //JCP settings dir 02/10/2009
261 const std::string settingsdirectory = GetUserSettingsDirectory();
262 //boost::algorithm::replace_all( mUserSettingsDirectory,
263 // INVALID_FILE_SEPARATOR ,
264 // VALID_FILE_SEPARATOR);
266 //("C:\\Documents and Settings\\cervenansky\\.gimmick\\"); // settingsdirectory );
268 isdir = boost::filesystem::is_directory(settingsdirectory); // settingsdirectory );
271 GimmickMessage(1,"Directory '"<<GetUserSettingsDirectory()<<"' "
272 << "does not exist : creating it"<<std::endl);
274 if ( ! boost::filesystem::create_directory( GetUserSettingsDirectory() ) )
276 GimmickError("ERROR CREATING '"<<GetUserSettingsDirectory()<<"'");
280 std::string setDir=GetUserSettingsDirectory();
281 boost::algorithm::replace_all( setDir,
282 INVALID_FILE_SEPARATOR ,
283 VALID_FILE_SEPARATOR);
285 boost::filesystem::create_directory( setDir );
286 setDir+="creaImageIO/";
287 boost::filesystem::create_directory( setDir );
288 setDir+=mLocalDescpName;
290 if(!boost::filesystem::is_regular(setDir))
293 crea::System::GetAppPath(name,PATH_MAX);
294 std::cout<<name<<std::endl;
296 std::string path=name;
297 path=path.substr(0,path.size()-1);
298 path=path.substr(0,path.find_last_of("/"));
299 //Creating directories
301 // The following stuff works on Linux, NOT CHECKED on Windows // JPR
304 path+="/bin/share/creaImageIO/";
308 path+="/../share/creaImageIO/";
310 #if defined(__APPLE__)
311 path+="/../../../../share/creaImageIO/";
315 path+= mLocalDescpName;
317 std::cout <<"From: " << path <<std::endl;
318 std::cout <<"To: " << setDir <<std::endl;
319 boost::algorithm::replace_all( path,
320 INVALID_FILE_SEPARATOR ,
321 VALID_FILE_SEPARATOR);
322 boost::filesystem::copy_file(path,setDir);
326 //========================================================================
329 //========================================================================
330 /// Sets message level
331 void Gimmick::SetMessageLevel(int l)
333 SetGimmickMessageLevel(l);
335 //========================================================================
337 //========================================================================
338 /// Sets message level
339 void Gimmick::SetDebugMessageLevel(int l)
341 SetGimmickDebugMessageLevel(l);
343 //========================================================================
345 //========================================================================
346 /// Returns the tree handler with the given name
347 TreeHandler* Gimmick::GetTreeHandler(const std::string& name) const
349 TreeHandlerMapType::const_iterator i;
350 i = GetTreeHandlerMap().find(name);
351 if ( i == GetTreeHandlerMap().end() )
353 GimmickError("TreeHandler '"<<name<<"' does not exist");
358 //========================================================================
359 /// Add the files to the tree handler
360 void Gimmick::AddFiles(const std::string& d,
361 const std::vector<std::string>& filenames)
363 GimmickMessage(2,"Adding files to '"<<d<<"'"<<std::endl);
365 mImageAdder.SetCurrentDatabase(d);
366 mImageAdder.SetTreeHandler(GetTreeHandler(d));
367 mImageAdder.SetSynchronizer(mSynchronizer);
368 mImageAdder.AddFiles(filenames);
370 //========================================================================
372 //========================================================================
373 /// Add a dir to the local database
374 void Gimmick::AddDir(const std::string& d, const std::string& f,
377 GimmickMessage(2,"Adding dir '"<<f<<"' to '"<<d<<"' recurse:"
378 <<recurse<<std::endl);
380 TreeHandler * handler=GetTreeHandler(d);
381 mImageAdder.SetCurrentDatabase(d);
382 mImageAdder.SetTreeHandler(handler);
383 mImageAdder.SetSynchronizer(mSynchronizer);
384 mImageAdder.AddDirectory(f,recurse);
387 //========================================================================
389 //========================================================================
390 void Gimmick::RemoveFile(const std::string& d,
393 mImageAdder.SetCurrentDatabase(d);
394 mImageAdder.SetSynchronizer(mSynchronizer);
395 mImageAdder.RemoveFile(node);
397 //========================================================================
399 //void Gimmick::Anonymize(std::vector<std::string>i_files) { }
400 //========================================================================
402 void Gimmick::CopyFiles(const std::vector<std::string>& filenames, const std::string& d )
404 TreeHandler * handler=GetTreeHandler(d);
405 mImageAdder.SetCurrentDatabase(d);
406 mImageAdder.SetTreeHandler(handler);
407 mImageAdder.SetSynchronizer(mSynchronizer);
408 mImageAdder.CopyFiles(filenames, mSettings->getValue(SETTINGS_COPY_PATH));
411 //========================================================================
413 std::string Gimmick::Synchronize(const std::string& d, bool repair, bool checkAttributes)
415 TreeHandler * handler=GetTreeHandler(d);
416 mImageAdder.SetCurrentDatabase(d);
417 mImageAdder.SetTreeHandler(handler);
418 mImageAdder.SetSynchronizer(mSynchronizer);
419 return mImageAdder.Synchronize(repair, checkAttributes);
422 //========================================================================
424 void Gimmick::Print(const std::string& d)
426 GetTreeHandler(d)->GetTree().Print();
428 //========================================================================
430 void Gimmick::GetSetting(const std::string& name, std::string& value)
432 value = mSettings->getValue(name);
434 //========================================================================
436 //========================================================================
438 void Gimmick::GetAttributes(const std::string& d,
439 const std::string& filename,
440 const std::vector<std::string>& params,
441 std::vector<std::string>& results)
443 TreeHandler * handler=GetTreeHandler(d);
444 mImageAdder.SetCurrentDatabase(d);
445 mImageAdder.SetTreeHandler(handler);
446 mImageAdder.SetSynchronizer(mSynchronizer);
447 mImageAdder.GetAttributes(params, filename, results);
449 //========================================================================
451 //========================================================================
452 // get attributes values from database for a given file from database
453 //========================================================================
454 void Gimmick::GetAttributes(const std::string filename, std::map<std::string, std::string> &i_res, OutputAttr i_attr)
456 if (i_attr.inside.size() > 0)
458 std::map<std::string, std::string> map_attr;
459 TreeHandler * handler=GetTreeHandler(i_attr.db);
460 handler->getAllAttributes(filename, map_attr);
461 if(i_attr.inside.front() == "ALL") // we take all values
463 std::map<std::string, std::string>::iterator it = map_attr.begin();
464 for(; it != map_attr.end(); it++)
465 i_res[it->first] = it->second;
469 std::vector<std::string>::iterator it = i_attr.inside.begin();
470 for(; it != i_attr.inside.end(); it++)
471 i_res[(*it)] = map_attr[(*it)];
477 //========================================================================
479 void Gimmick::UpdateSetting(const std::string& name, const std::string& value)
481 mSettings->updateSetting(name,value);
482 mSettings->writeSettingsFile();
484 //========================================================================
486 void Gimmick::DeleteDrive(const std::string& drive)
488 for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
489 it!= mTreeHandlerMap.end();
492 mImageAdder.SetTreeHandler(it->second);
493 mImageAdder.DeleteDriveFromMainDB(drive);
495 mImageAdder.SetSynchronizer(mSynchronizer);
496 mImageAdder.DeleteDriveFromOtherDB(drive);
499 //========================================================================
500 void Gimmick::EditField(tree::Node* node, const std::string& d, const std::string& name, const std::string& key, const std::string& val)
502 TreeHandler * handler=GetTreeHandler(d);
503 mImageAdder.SetCurrentDatabase(d);
504 mImageAdder.SetTreeHandler(handler);
505 mImageAdder.EditField(node,name,key,val);
507 //========================================================================
509 ////////////////////////////////////////////////////////////////////////
510 // add DB from Settings file //
513 ////////////////////////////////////////////////////////////////////////
514 void Gimmick::addDBSettings()
517 std::string pathSettings = mSettings->getValue(SETTINGS_DBPATH);
519 // split to find all paths
520 std::vector<std::string> paths;
521 std::string separator = ";";
522 std::string::size_type last_pos = pathSettings.find_first_not_of(separator);
523 //find first separator
524 std::string::size_type pos = pathSettings.find_first_of(separator, last_pos);
525 while(std::string::npos != pos || std::string::npos != last_pos)
527 paths.push_back(pathSettings.substr(last_pos, pos - last_pos));
528 last_pos = pathSettings.find_first_not_of(separator, pos);
529 pos = pathSettings.find_first_of(separator, last_pos);
532 std::vector<std::string>::iterator it_path = paths.begin();
533 for(; it_path != paths.end(); ++it_path)
535 pos = it_path->find_last_of("\\");
536 last_pos = it_path->find_last_of(".");
537 std::string name = it_path->substr(pos +1, last_pos -pos-1 );
538 addDB(name, it_path->c_str());
543 ///////////////////////////////////////////////////////////////////////////////
544 // Fill attributes structure with attributes present in database (inside vector
545 // and not present (outside)
546 ///////////////////////////////////////////////////////////////////////////////
547 void Gimmick::fillVectInfos(std::vector<std::string> i_attr, OutputAttr &infos)
549 //test if a tag is present in Database descriptor
550 TreeHandler * handler=GetTreeHandler(infos.db);
551 mImageAdder.SetTreeHandler(handler);
552 std::vector<std::string>::const_iterator it = i_attr.begin();
553 for (;it != i_attr.end(); it++)
555 if( mImageAdder.isAttributeExist((*it)) != "" ) // in DB
557 printf("EED Gimmick::fillVectInfos inside %s\n",(*it).c_str());
558 infos.inside.push_back((*it));
562 infos.outside.push_back((*it)); // Need to scan again the files
563 printf("EED Gimmick::fillVectInfos outside %s\n",(*it).c_str());
568 const std::string Gimmick::getSummary()
570 const AddProgress& p = GetAddProgress();
571 std::stringstream mess;
572 mess << "Dirs \tscanned\t: " << p.GetNumberScannedDirs() << "\n";
573 mess << "Files\tscanned\t: " << p.GetNumberScannedFiles() << "\n";
574 mess << "Files\thandled\t: " << p.GetNumberHandledFiles() << "\n\n";
575 mess << "Files\tadded \t: " << p.GetNumberAddedFiles() << "\n\n";