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 //==============================================================
69 mSettings->writeSettingsFile();
77 //==============================================================
79 //==============================================================
80 void Gimmick::Initialize(const std::string i_namedescp, const std::string i_namedb)
82 mLocalDescpName = i_namedescp;
83 mLocalDBName = i_namedb;
87 //==============================================================
88 void Gimmick::Initialize()
90 std::string i_nameDB = mLocalDBName;
91 // Create the UserSettings dir if does not exist
92 CreateUserSettingsDirectory();
93 // Sets the current directory to the home dir
94 mCurrentDirectory = GetHomeDirectory();
95 mSynchronizer= new Synchronizer(GetUserSettingsDirectory()+"share/creaImageIO/");
97 mSettings = new Settings(mCurrentDirectory);
99 std::string dbpath = GetLocalDatabasePath();
101 // Create or open local database
102 std::string dpath= mCurrentDirectory + "/.creaImageIO/share/creaImageIO/" + mLocalDescpName;
104 boost::algorithm::replace_all( dpath,
105 INVALID_FILE_SEPARATOR ,
106 VALID_FILE_SEPARATOR);
107 mLocalDatabase = createDB(i_nameDB, dpath, dbpath);
108 // Add it to the TreeHandlerMap
109 mTreeHandlerMap[i_nameDB] = mLocalDatabase;
111 //Add additional DB from user Settings
115 ///////////////////////////////////////////////////////////////////////
116 // add DB to TreeHandler Map //
117 // @param i_name : DB name //
118 // @param i_location : DB location //
120 ////////////////////////////////////////////////////////////////////////
121 void Gimmick::addDB(const std::string &i_name,
122 const std::string &i_location)
124 if(mTreeHandlerMap.find(i_name) == mTreeHandlerMap.end())
126 mTreeHandlerMap[i_name] = new SQLiteTreeHandler(i_location);
127 mTreeHandlerMap[i_name]->Open(true);
128 mSettings->addDB(i_location);
132 ///////////////////////////////////////////////////////////////////////////
133 // create a DB from a attributes descriptor file for medical images //
134 // @param i_name : DB name //
135 // @param i_locDesc : location of descriptor file //
136 // @param i_locDB : location of DB //
137 // return : the SQLiteTreeHandler object on DB //
138 /////////////////////////////////////////////////////////////////////////
139 SQLiteTreeHandler* Gimmick::createDB(const std::string &i_name,
140 const std::string &i_locDesc,
141 const std::string &i_locDB)
143 SQLiteTreeHandler* sqlTreeH( new SQLiteTreeHandler(i_locDB) );
144 // Create or open local database
145 if (! boost::filesystem::exists(i_locDB) )
147 std::string mess = "Local database '";
149 mess += "' does not exist : creating it";
150 GimmickMessage(1,mess<<std::endl);
152 // CREATING DB STRUCTURE
153 sqlTreeH->GetTree().GetDescriptor().createDescriptorfromFile(i_locDesc);
154 if ( ! sqlTreeH->Create(true) )
156 GimmickError("ERROR CREATING '"<<i_locDB<<"'");
158 sqlTreeH->SetAttribute(0,"Name",i_name);
164 GimmickDebugMessage(1,"Opening local database '" <<i_locDB<< "' " << std::endl);
165 if ( !sqlTreeH->Open(true) )
167 GimmickError("ERROR OPENING '"<<i_locDB<<"'");
173 //==============================================================
174 void Gimmick::Finalize()
176 if(mTreeHandlerMap.size() >0)
178 // delete SQLiteTreeHandler Object
179 for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
180 it!= mTreeHandlerMap.end();
187 //==============================================================
189 //================================================================
192 #define VALID_FILE_SEPARATOR "\\"
193 #define INVALID_FILE_SEPARATOR "/"
195 #define INVALID_FILE_SEPARATOR "\\"
196 #define VALID_FILE_SEPARATOR "/"
198 //================================================================
200 //================================================================
201 const std::string& Gimmick::GetHomeDirectory()
203 if (mHomeDirectory.size()==0)
205 #if defined(__GNUC__)
206 mHomeDirectory = getenv("HOME");
207 #elif defined(_WIN32)
208 mHomeDirectory = getenv("USERPROFILE");
211 return mHomeDirectory;
213 //================================================================
214 const std::string& Gimmick::GetUserSettingsDirectory()
216 if (mUserSettingsDirectory.size()==0)
218 mUserSettingsDirectory = GetHomeDirectory();
219 mUserSettingsDirectory += "/.creaImageIO/";
220 boost::algorithm::replace_all( mUserSettingsDirectory,
221 INVALID_FILE_SEPARATOR ,
222 VALID_FILE_SEPARATOR);
224 return mUserSettingsDirectory;
226 //================================================================
229 //================================================================
230 const std::string& Gimmick::GetLocalDatabasePath()
232 if (mLocalDatabasePath.size()==0)
234 mLocalDatabasePath = GetUserSettingsDirectory();
235 mLocalDatabasePath += "share/creaImageIO/";
236 mLocalDatabasePath += mLocalDBName;
237 mLocalDatabasePath +=".sqlite3";
238 boost::algorithm::replace_all( mLocalDatabasePath,
239 INVALID_FILE_SEPARATOR ,
240 VALID_FILE_SEPARATOR);
242 return mLocalDatabasePath;
245 //========================================================================
247 //========================================================================
248 void Gimmick::CreateUserSettingsDirectory()
251 // std::string st("C:/Documents and Settings/cervenansky/.gimmick/");
252 // boost::algorithm::replace_all( st,
253 // INVALID_FILE_SEPARATOR ,
254 // VALID_FILE_SEPARATOR);
255 //const boost::filesystem::path mpath(st);
256 //C:\Documents and Settings\cervenansky\.gimmick");
257 //if ( !boost::filesystem::exists( path ) ) return ;
258 // boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
259 // for ( boost::filesystem::directory_iterator itr( path ); itr != end_itr; ++itr )
261 //// If is directory & recurse : do recurse
262 // if ( boost::filesystem::is_directory(itr->status()) )
266 //JCP settings dir 02/10/2009
267 const std::string settingsdirectory = GetUserSettingsDirectory();
268 //boost::algorithm::replace_all( mUserSettingsDirectory,
269 // INVALID_FILE_SEPARATOR ,
270 // VALID_FILE_SEPARATOR);
272 //("C:\\Documents and Settings\\cervenansky\\.gimmick\\"); // settingsdirectory );
274 isdir = boost::filesystem::is_directory(settingsdirectory); // settingsdirectory );
277 GimmickMessage(1,"Directory '"<<GetUserSettingsDirectory()<<"' "
278 << "does not exist : creating it"<<std::endl);
280 if ( ! boost::filesystem::create_directory( GetUserSettingsDirectory() ) )
282 GimmickError("ERROR CREATING '"<<GetUserSettingsDirectory()<<"'");
286 std::string setDir=GetUserSettingsDirectory();
287 boost::algorithm::replace_all( setDir,
288 INVALID_FILE_SEPARATOR ,
289 VALID_FILE_SEPARATOR);
291 boost::filesystem::create_directory( setDir );
292 setDir+="creaImageIO/";
293 boost::filesystem::create_directory( setDir );
294 setDir+=mLocalDescpName;
296 if(!boost::filesystem::is_regular(setDir))
299 crea::System::GetAppPath(name,PATH_MAX);
300 std::cout<<name<<std::endl;
302 std::string path=name;
303 path=path.substr(0,path.size()-1);
304 path=path.substr(0,path.find_last_of("/"));
305 //Creating directories
307 // The following stuff works on Linux, NOT CHECKED on Windows // JPR
310 path+="/bin/share/creaImageIO/";
314 path+="/../share/creaImageIO/";
316 #if defined(__APPLE__)
317 path+="/../../../../share/creaImageIO/";
321 path+= mLocalDescpName;
323 std::cout <<"From: " << path <<std::endl;
324 std::cout <<"To: " << setDir <<std::endl;
325 boost::algorithm::replace_all( path,
326 INVALID_FILE_SEPARATOR ,
327 VALID_FILE_SEPARATOR);
328 boost::filesystem::copy_file(path,setDir);
332 //========================================================================
335 //========================================================================
336 /// Sets message level
337 void Gimmick::SetMessageLevel(int l)
339 SetGimmickMessageLevel(l);
341 //========================================================================
343 //========================================================================
344 /// Sets message level
345 void Gimmick::SetDebugMessageLevel(int l)
347 SetGimmickDebugMessageLevel(l);
349 //========================================================================
351 //========================================================================
352 /// Returns the tree handler with the given name
353 TreeHandler* Gimmick::GetTreeHandler(const std::string& name) const
355 TreeHandlerMapType::const_iterator i;
356 i = GetTreeHandlerMap().find(name);
357 if ( i == GetTreeHandlerMap().end() )
359 GimmickError("TreeHandler '"<<name<<"' does not exist");
364 //========================================================================
365 /// Add the files to the tree handler
366 void Gimmick::AddFiles(const std::string& d,
367 const std::vector<std::string>& filenames)
369 GimmickMessage(2,"Adding files to '"<<d<<"'"<<std::endl);
371 mImageAdder.SetCurrentDatabase(d);
372 mImageAdder.SetTreeHandler(GetTreeHandler(d));
373 mImageAdder.SetSynchronizer(mSynchronizer);
374 mImageAdder.AddFiles(filenames);
376 //========================================================================
378 //========================================================================
379 /// Add a dir to the local database
380 void Gimmick::AddDir(const std::string& d, const std::string& f,
383 GimmickMessage(2,"Adding dir '"<<f<<"' to '"<<d<<"' recurse:"
384 <<recurse<<std::endl);
386 TreeHandler * handler=GetTreeHandler(d);
387 mImageAdder.SetCurrentDatabase(d);
388 mImageAdder.SetTreeHandler(handler);
389 mImageAdder.SetSynchronizer(mSynchronizer);
390 mImageAdder.AddDirectory(f,recurse);
393 //========================================================================
395 //========================================================================
396 void Gimmick::RemoveFile(const std::string& d,
399 mImageAdder.SetCurrentDatabase(d);
400 mImageAdder.SetSynchronizer(mSynchronizer);
401 mImageAdder.RemoveFile(node);
403 //========================================================================
405 //void Gimmick::Anonymize(std::vector<std::string>i_files) { }
406 //========================================================================
408 void Gimmick::CopyFiles(const std::vector<std::string>& filenames, const std::string& d )
410 TreeHandler * handler=GetTreeHandler(d);
411 mImageAdder.SetCurrentDatabase(d);
412 mImageAdder.SetTreeHandler(handler);
413 mImageAdder.SetSynchronizer(mSynchronizer);
414 mImageAdder.CopyFiles(filenames, mSettings->getValue(SETTINGS_COPY_PATH));
417 //========================================================================
419 std::string Gimmick::Synchronize(const std::string& d, bool repair, bool checkAttributes)
421 TreeHandler * handler=GetTreeHandler(d);
422 mImageAdder.SetCurrentDatabase(d);
423 mImageAdder.SetTreeHandler(handler);
424 mImageAdder.SetSynchronizer(mSynchronizer);
425 return mImageAdder.Synchronize(repair, checkAttributes);
428 //========================================================================
430 void Gimmick::Print(const std::string& d)
432 GetTreeHandler(d)->GetTree().Print();
434 //========================================================================
436 void Gimmick::GetSetting(const std::string& name, std::string& value)
438 value = mSettings->getValue(name);
440 //========================================================================
442 //========================================================================
444 void Gimmick::GetAttributes(const std::string& d,
445 const std::string& filename,
446 const std::vector<std::string>& params,
447 std::vector<std::string>& results)
449 TreeHandler * handler=GetTreeHandler(d);
450 mImageAdder.SetCurrentDatabase(d);
451 mImageAdder.SetTreeHandler(handler);
452 mImageAdder.SetSynchronizer(mSynchronizer);
453 mImageAdder.GetAttributes(params, filename, results);
455 //========================================================================
457 //========================================================================
458 // get attributes values from database for a given file from database
459 //========================================================================
460 void Gimmick::GetAttributes(const std::string filename, std::map<std::string, std::string> &i_res, OutputAttr i_attr)
462 if (i_attr.inside.size() > 0)
464 std::map<std::string, std::string> map_attr;
465 TreeHandler * handler=GetTreeHandler(i_attr.db);
466 handler->getAllAttributes(filename, map_attr);
467 if(i_attr.inside.front() == "ALL") // we take all values
469 std::map<std::string, std::string>::iterator it = map_attr.begin();
470 for(; it != map_attr.end(); it++)
471 i_res[it->first] = it->second;
475 std::vector<std::string>::iterator it = i_attr.inside.begin();
476 for(; it != i_attr.inside.end(); it++)
477 i_res[(*it)] = map_attr[(*it)];
483 //========================================================================
485 void Gimmick::UpdateSetting(const std::string& name, const std::string& value)
487 mSettings->updateSetting(name,value);
488 mSettings->writeSettingsFile();
490 //========================================================================
492 void Gimmick::DeleteDrive(const std::string& drive)
494 for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
495 it!= mTreeHandlerMap.end();
498 mImageAdder.SetTreeHandler(it->second);
499 mImageAdder.DeleteDriveFromMainDB(drive);
501 mImageAdder.SetSynchronizer(mSynchronizer);
502 mImageAdder.DeleteDriveFromOtherDB(drive);
505 //========================================================================
506 void Gimmick::EditField(tree::Node* node, const std::string& d, const std::string& name, const std::string& key, const std::string& val)
508 TreeHandler * handler=GetTreeHandler(d);
509 mImageAdder.SetCurrentDatabase(d);
510 mImageAdder.SetTreeHandler(handler);
511 mImageAdder.EditField(node,name,key,val);
513 //========================================================================
515 ////////////////////////////////////////////////////////////////////////
516 // add DB from Settings file //
519 ////////////////////////////////////////////////////////////////////////
520 void Gimmick::addDBSettings()
523 std::string pathSettings = mSettings->getValue(SETTINGS_DBPATH);
525 // split to find all paths
526 std::vector<std::string> paths;
527 std::string separator = ";";
528 std::string::size_type last_pos = pathSettings.find_first_not_of(separator);
529 //find first separator
530 std::string::size_type pos = pathSettings.find_first_of(separator, last_pos);
531 while(std::string::npos != pos || std::string::npos != last_pos)
533 paths.push_back(pathSettings.substr(last_pos, pos - last_pos));
534 last_pos = pathSettings.find_first_not_of(separator, pos);
535 pos = pathSettings.find_first_of(separator, last_pos);
538 std::vector<std::string>::iterator it_path = paths.begin();
539 for(; it_path != paths.end(); ++it_path)
541 pos = it_path->find_last_of("\\");
542 last_pos = it_path->find_last_of(".");
543 std::string name = it_path->substr(pos +1, last_pos -pos-1 );
544 addDB(name, it_path->c_str());
549 ///////////////////////////////////////////////////////////////////////////////
550 // Fill attributes structure with attributes present in database (inside vector
551 // and not present (outside)
552 ///////////////////////////////////////////////////////////////////////////////
553 void Gimmick::fillVectInfos(std::vector<std::string> i_attr, OutputAttr &infos)
555 //test if a tag is present in Database descriptor
556 TreeHandler * handler=GetTreeHandler(infos.db);
557 mImageAdder.SetTreeHandler(handler);
558 std::vector<std::string>::const_iterator it = i_attr.begin();
559 for (;it != i_attr.end(); it++)
561 if( mImageAdder.isAttributeExist((*it)) != "" ) // in DB
563 infos.inside.push_back((*it));
567 infos.outside.push_back((*it)); // Need to scan again the files
572 const std::string Gimmick::getSummary()
574 const AddProgress& p = GetAddProgress();
575 std::stringstream mess;
576 mess << "Dirs \tscanned\t: " << p.GetNumberScannedDirs() << "\n";
577 mess << "Files\tscanned\t: " << p.GetNumberScannedFiles() << "\n";
578 mess << "Files\thandled\t: " << p.GetNumberHandledFiles() << "\n\n";
579 mess << "Files\tadded \t: " << p.GetNumberAddedFiles() << "\n\n";