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>
29 #include <creaImageIOSystem.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>
46 //==============================================================
50 RegisterGimmickMessageTypes();
53 mLocalDescpName = "localdatabase_Descriptor.dscp";
54 mLocalDBName = "Local database";
56 //==============================================================
59 //==============================================================
65 mSettings->writeSettingsFile();
73 //==============================================================
75 //==============================================================
76 void Gimmick::Initialize(const std::string i_namedescp, const std::string i_namedb)
78 mLocalDescpName = i_namedescp;
79 mLocalDBName = i_namedb;
83 //==============================================================
84 void Gimmick::Initialize()
86 std::string i_nameDB = mLocalDBName;
87 // Create the UserSettings dir if does not exist
88 CreateUserSettingsDirectory();
89 // Sets the current directory to the home dir
90 mCurrentDirectory = GetHomeDirectory();
91 mSynchronizer= new Synchronizer(GetUserSettingsDirectory()+"share/creaImageIO/");
93 mSettings = new Settings(mCurrentDirectory);
95 std::string dbpath = GetLocalDatabasePath();
97 // Create or open local database
98 std::string dpath= mCurrentDirectory + "/.creaImageIO/share/creaImageIO/" + mLocalDescpName;
100 boost::algorithm::replace_all( dpath,
101 INVALID_FILE_SEPARATOR ,
102 VALID_FILE_SEPARATOR);
103 mLocalDatabase = createDB(i_nameDB, dpath, dbpath);
104 // Add it to the TreeHandlerMap
105 mTreeHandlerMap[i_nameDB] = mLocalDatabase;
107 //Add additional DB from user Settings
111 ///////////////////////////////////////////////////////////////////////
112 // add DB to TreeHandler Map //
113 // @param i_name : DB name //
114 // @param i_location : DB location //
116 ////////////////////////////////////////////////////////////////////////
117 void Gimmick::addDB(const std::string &i_name,
118 const std::string &i_location)
120 if(mTreeHandlerMap.find(i_name) == mTreeHandlerMap.end())
122 mTreeHandlerMap[i_name] = new SQLiteTreeHandler(i_location);
123 mTreeHandlerMap[i_name]->Open(true);
124 mSettings->addDB(i_location);
128 ///////////////////////////////////////////////////////////////////////////
129 // create a DB from a attributes descriptor file for medical images //
130 // @param i_name : DB name //
131 // @param i_locDesc : location of descriptor file //
132 // @param i_locDB : location of DB //
133 // return : the SQLiteTreeHandler object on DB //
134 /////////////////////////////////////////////////////////////////////////
135 SQLiteTreeHandler* Gimmick::createDB(const std::string &i_name,
136 const std::string &i_locDesc,
137 const std::string &i_locDB)
139 SQLiteTreeHandler* sqlTreeH( new SQLiteTreeHandler(i_locDB) );
140 // Create or open local database
141 if (! boost::filesystem::exists(i_locDB) )
143 std::string mess = "Local database '";
145 mess += "' does not exist : creating it";
146 GimmickMessage(1,mess<<std::endl);
148 // CREATING DB STRUCTURE
149 sqlTreeH->GetTree().GetDescriptor().createDescriptorfromFile(i_locDesc);
150 if ( ! sqlTreeH->Create(true) )
152 GimmickError("ERROR CREATING '"<<i_locDB<<"'");
154 sqlTreeH->SetAttribute(0,"Name",i_name);
160 GimmickDebugMessage(1,"Opening local database '" <<i_locDB<< "' " << std::endl);
161 if ( !sqlTreeH->Open(true) )
163 GimmickError("ERROR OPENING '"<<i_locDB<<"'");
169 //==============================================================
170 void Gimmick::Finalize()
172 if(mTreeHandlerMap.size() >0)
174 // delete SQLiteTreeHandler Object
175 for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
176 it!= mTreeHandlerMap.end();
183 //==============================================================
185 //================================================================
188 #define VALID_FILE_SEPARATOR "\\"
189 #define INVALID_FILE_SEPARATOR "/"
191 #define INVALID_FILE_SEPARATOR "\\"
192 #define VALID_FILE_SEPARATOR "/"
194 //================================================================
196 //================================================================
197 const std::string& Gimmick::GetHomeDirectory()
199 if (mHomeDirectory.size()==0)
201 #if defined(__GNUC__)
202 mHomeDirectory = getenv("HOME");
203 #elif defined(_WIN32)
204 mHomeDirectory = getenv("USERPROFILE");
207 return mHomeDirectory;
209 //================================================================
210 const std::string& Gimmick::GetUserSettingsDirectory()
212 if (mUserSettingsDirectory.size()==0)
214 mUserSettingsDirectory = GetHomeDirectory();
215 mUserSettingsDirectory += "/.creaImageIO/";
216 boost::algorithm::replace_all( mUserSettingsDirectory,
217 INVALID_FILE_SEPARATOR ,
218 VALID_FILE_SEPARATOR);
220 return mUserSettingsDirectory;
222 //================================================================
225 //================================================================
226 const std::string& Gimmick::GetLocalDatabasePath()
228 if (mLocalDatabasePath.size()==0)
230 mLocalDatabasePath = GetUserSettingsDirectory();
231 mLocalDatabasePath += "share/creaImageIO/";
232 mLocalDatabasePath += mLocalDBName;
233 mLocalDatabasePath +=".sqlite3";
234 boost::algorithm::replace_all( mLocalDatabasePath,
235 INVALID_FILE_SEPARATOR ,
236 VALID_FILE_SEPARATOR);
238 return mLocalDatabasePath;
241 //========================================================================
243 //========================================================================
244 void Gimmick::CreateUserSettingsDirectory()
247 // std::string st("C:/Documents and Settings/cervenansky/.gimmick/");
248 // boost::algorithm::replace_all( st,
249 // INVALID_FILE_SEPARATOR ,
250 // VALID_FILE_SEPARATOR);
251 //const boost::filesystem::path mpath(st);
252 //C:\Documents and Settings\cervenansky\.gimmick");
253 //if ( !boost::filesystem::exists( path ) ) return ;
254 // boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
255 // for ( boost::filesystem::directory_iterator itr( path ); itr != end_itr; ++itr )
257 //// If is directory & recurse : do recurse
258 // if ( boost::filesystem::is_directory(itr->status()) )
262 //JCP settings dir 02/10/2009
263 const std::string settingsdirectory = GetUserSettingsDirectory();
264 //boost::algorithm::replace_all( mUserSettingsDirectory,
265 // INVALID_FILE_SEPARATOR ,
266 // VALID_FILE_SEPARATOR);
268 //("C:\\Documents and Settings\\cervenansky\\.gimmick\\"); // settingsdirectory );
270 isdir = boost::filesystem::is_directory(settingsdirectory); // settingsdirectory );
273 GimmickMessage(1,"Directory '"<<GetUserSettingsDirectory()<<"' "
274 << "does not exist : creating it"<<std::endl);
276 if ( ! boost::filesystem::create_directory( GetUserSettingsDirectory() ) )
278 GimmickError("ERROR CREATING '"<<GetUserSettingsDirectory()<<"'");
282 std::string setDir=GetUserSettingsDirectory();
283 boost::algorithm::replace_all( setDir,
284 INVALID_FILE_SEPARATOR ,
285 VALID_FILE_SEPARATOR);
287 boost::filesystem::create_directory( setDir );
288 setDir+="creaImageIO/";
289 boost::filesystem::create_directory( setDir );
290 setDir+=mLocalDescpName;
292 if(!boost::filesystem::is_regular(setDir))
295 crea::System::GetAppPath(name,PATH_MAX);
296 std::cout<<name<<std::endl;
298 std::string path=name;
299 path=path.substr(0,path.size()-1);
300 path=path.substr(0,path.find_last_of("/"));
301 //Creating directories
303 // The following stuff works on Linux, NOT CHECKED on Windows // JPR
306 path+="/bin/share/creaImageIO/";
310 path+="/../share/creaImageIO/";
312 #if defined(__APPLE__)
313 path+="/../../../../share/creaImageIO/";
317 path+= mLocalDescpName;
319 std::cout <<"From: " << path <<std::endl;
320 std::cout <<"To: " << setDir <<std::endl;
321 boost::algorithm::replace_all( path,
322 INVALID_FILE_SEPARATOR ,
323 VALID_FILE_SEPARATOR);
324 boost::filesystem::copy_file(path,setDir);
328 //========================================================================
331 //========================================================================
332 /// Sets message level
333 void Gimmick::SetMessageLevel(int l)
335 SetGimmickMessageLevel(l);
337 //========================================================================
339 //========================================================================
340 /// Sets message level
341 void Gimmick::SetDebugMessageLevel(int l)
343 SetGimmickDebugMessageLevel(l);
345 //========================================================================
347 //========================================================================
348 /// Returns the tree handler with the given name
349 TreeHandler* Gimmick::GetTreeHandler(const std::string& name) const
351 TreeHandlerMapType::const_iterator i;
352 i = GetTreeHandlerMap().find(name);
353 if ( i == GetTreeHandlerMap().end() )
355 GimmickError("TreeHandler '"<<name<<"' does not exist");
360 //========================================================================
361 /// Add the files to the tree handler
362 void Gimmick::AddFiles(const std::string& d,
363 const std::vector<std::string>& filenames)
365 GimmickMessage(2,"Adding files to '"<<d<<"'"<<std::endl);
367 mImageAdder.SetCurrentDatabase(d);
368 mImageAdder.SetTreeHandler(GetTreeHandler(d));
369 mImageAdder.SetSynchronizer(mSynchronizer);
370 mImageAdder.AddFiles(filenames);
372 //========================================================================
374 //========================================================================
375 /// Add a dir to the local database
376 void Gimmick::AddDir(const std::string& d, const std::string& f,
379 GimmickMessage(2,"Adding dir '"<<f<<"' to '"<<d<<"' recurse:"
380 <<recurse<<std::endl);
382 TreeHandler * handler=GetTreeHandler(d);
383 mImageAdder.SetCurrentDatabase(d);
384 mImageAdder.SetTreeHandler(handler);
385 mImageAdder.SetSynchronizer(mSynchronizer);
386 mImageAdder.AddDirectory(f,recurse);
389 //========================================================================
391 //========================================================================
392 void Gimmick::RemoveFile(const std::string& d,
395 mImageAdder.SetCurrentDatabase(d);
396 mImageAdder.SetSynchronizer(mSynchronizer);
397 mImageAdder.RemoveFile(node);
399 //========================================================================
401 //void Gimmick::Anonymize(std::vector<std::string>i_files) { }
402 //========================================================================
404 void Gimmick::CopyFiles(const std::vector<std::string>& filenames, const std::string& d )
406 TreeHandler * handler=GetTreeHandler(d);
407 mImageAdder.SetCurrentDatabase(d);
408 mImageAdder.SetTreeHandler(handler);
409 mImageAdder.SetSynchronizer(mSynchronizer);
410 mImageAdder.CopyFiles(filenames, mSettings->getValue(SETTINGS_COPY_PATH));
413 //========================================================================
415 std::string Gimmick::Synchronize(const std::string& d, bool repair, bool checkAttributes)
417 TreeHandler * handler=GetTreeHandler(d);
418 mImageAdder.SetCurrentDatabase(d);
419 mImageAdder.SetTreeHandler(handler);
420 mImageAdder.SetSynchronizer(mSynchronizer);
421 return mImageAdder.Synchronize(repair, checkAttributes);
424 //========================================================================
426 void Gimmick::Print(const std::string& d)
428 GetTreeHandler(d)->GetTree().Print();
430 //========================================================================
432 void Gimmick::GetSetting(const std::string& name, std::string& value)
434 value = mSettings->getValue(name);
436 //========================================================================
438 //========================================================================
440 void Gimmick::GetAttributes(const std::string& d,
441 const std::string& filename,
442 const std::vector<std::string>& params,
443 std::vector<std::string>& results)
445 TreeHandler * handler=GetTreeHandler(d);
446 mImageAdder.SetCurrentDatabase(d);
447 mImageAdder.SetTreeHandler(handler);
448 mImageAdder.SetSynchronizer(mSynchronizer);
449 mImageAdder.GetAttributes(params, filename, results);
451 //========================================================================
453 //========================================================================
454 // get attributes values from database for a given file from database
455 //========================================================================
456 void Gimmick::GetAttributes(const std::string filename, std::map<std::string, std::string> &i_res, OutputAttr i_attr)
458 if (i_attr.inside.size() > 0)
460 std::map<std::string, std::string> map_attr;
461 TreeHandler * handler=GetTreeHandler(i_attr.db);
462 handler->getAllAttributes(filename, map_attr);
463 if(i_attr.inside.front() == "ALL") // we take all values
465 std::map<std::string, std::string>::iterator it = map_attr.begin();
466 for(; it != map_attr.end(); it++)
467 i_res[it->first] = it->second;
471 std::vector<std::string>::iterator it = i_attr.inside.begin();
472 for(; it != i_attr.inside.end(); it++)
473 i_res[(*it)] = map_attr[(*it)];
479 //========================================================================
481 void Gimmick::UpdateSetting(const std::string& name, const std::string& value)
483 mSettings->updateSetting(name,value);
484 mSettings->writeSettingsFile();
486 //========================================================================
488 void Gimmick::DeleteDrive(const std::string& drive)
490 for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
491 it!= mTreeHandlerMap.end();
494 mImageAdder.SetTreeHandler(it->second);
495 mImageAdder.DeleteDriveFromMainDB(drive);
497 mImageAdder.SetSynchronizer(mSynchronizer);
498 mImageAdder.DeleteDriveFromOtherDB(drive);
501 //========================================================================
502 void Gimmick::EditField(tree::Node* node, const std::string& d, const std::string& name, const std::string& key, const std::string& val)
504 TreeHandler * handler=GetTreeHandler(d);
505 mImageAdder.SetCurrentDatabase(d);
506 mImageAdder.SetTreeHandler(handler);
507 mImageAdder.EditField(node,name,key,val);
509 //========================================================================
511 ////////////////////////////////////////////////////////////////////////
512 // add DB from Settings file //
515 ////////////////////////////////////////////////////////////////////////
516 void Gimmick::addDBSettings()
519 std::string pathSettings = mSettings->getValue(SETTINGS_DBPATH);
521 // split to find all paths
522 std::vector<std::string> paths;
523 std::string separator = ";";
524 std::string::size_type last_pos = pathSettings.find_first_not_of(separator);
525 //find first separator
526 std::string::size_type pos = pathSettings.find_first_of(separator, last_pos);
527 while(std::string::npos != pos || std::string::npos != last_pos)
529 paths.push_back(pathSettings.substr(last_pos, pos - last_pos));
530 last_pos = pathSettings.find_first_not_of(separator, pos);
531 pos = pathSettings.find_first_of(separator, last_pos);
534 std::vector<std::string>::iterator it_path = paths.begin();
535 for(; it_path != paths.end(); ++it_path)
537 pos = it_path->find_last_of("\\");
538 last_pos = it_path->find_last_of(".");
539 std::string name = it_path->substr(pos +1, last_pos -pos-1 );
540 addDB(name, it_path->c_str());
545 ///////////////////////////////////////////////////////////////////////////////
546 // Fill attributes structure with attributes present in database (inside vector
547 // and not present (outside)
548 ///////////////////////////////////////////////////////////////////////////////
549 void Gimmick::fillVectInfos(std::vector<std::string> i_attr, OutputAttr &infos)
551 //test if a tag is present in Database descriptor
552 TreeHandler * handler=GetTreeHandler(infos.db);
553 mImageAdder.SetTreeHandler(handler);
554 std::vector<std::string>::const_iterator it = i_attr.begin();
555 for (;it != i_attr.end(); it++)
557 if( mImageAdder.isAttributeExist((*it)) != "" ) // in DB
559 infos.inside.push_back((*it));
563 infos.outside.push_back((*it)); // Need to scan again the files
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";