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);
156 GimmickDebugMessage(1,"Opening local database '" <<i_locDB<< "' " << std::endl);
157 if ( !sqlTreeH->Open(true) )
159 GimmickError("ERROR OPENING '"<<i_locDB<<"'");
165 //==============================================================
166 void Gimmick::Finalize()
168 if(mTreeHandlerMap.size() >0)
170 // delete SQLiteTreeHandler Object
171 for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
172 it!= mTreeHandlerMap.end();
179 //==============================================================
181 //================================================================
184 #define VALID_FILE_SEPARATOR "\\"
185 #define INVALID_FILE_SEPARATOR "/"
187 #define INVALID_FILE_SEPARATOR "\\"
188 #define VALID_FILE_SEPARATOR "/"
190 //================================================================
192 //================================================================
193 const std::string& Gimmick::GetHomeDirectory()
195 if (mHomeDirectory.size()==0)
198 mHomeDirectory = getenv("USERPROFILE");
199 #elif defined(__GNUC__)
200 mHomeDirectory = getenv("HOME");
203 return mHomeDirectory;
205 //================================================================
206 const std::string& Gimmick::GetUserSettingsDirectory()
208 if (mUserSettingsDirectory.size()==0)
210 mUserSettingsDirectory = GetHomeDirectory();
211 mUserSettingsDirectory += "/.creaImageIO/";
212 boost::algorithm::replace_all( mUserSettingsDirectory,
213 INVALID_FILE_SEPARATOR ,
214 VALID_FILE_SEPARATOR);
216 return mUserSettingsDirectory;
218 //================================================================
221 //================================================================
222 const std::string& Gimmick::GetLocalDatabasePath()
224 if (mLocalDatabasePath.size()==0)
226 mLocalDatabasePath = GetUserSettingsDirectory();
227 mLocalDatabasePath += "share/creaImageIO/";
228 mLocalDatabasePath += mLocalDBName;
229 mLocalDatabasePath +=".sqlite3";
230 boost::algorithm::replace_all( mLocalDatabasePath,
231 INVALID_FILE_SEPARATOR ,
232 VALID_FILE_SEPARATOR);
234 return mLocalDatabasePath;
237 //========================================================================
239 //========================================================================
240 void Gimmick::CreateUserSettingsDirectory()
243 // std::string st("C:/Documents and Settings/cervenansky/.gimmick/");
244 // boost::algorithm::replace_all( st,
245 // INVALID_FILE_SEPARATOR ,
246 // VALID_FILE_SEPARATOR);
247 //const boost::filesystem::path mpath(st);
248 //C:\Documents and Settings\cervenansky\.gimmick");
249 //if ( !boost::filesystem::exists( path ) ) return ;
250 // boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
251 // for ( boost::filesystem::directory_iterator itr( path ); itr != end_itr; ++itr )
253 //// If is directory & recurse : do recurse
254 // if ( boost::filesystem::is_directory(itr->status()) )
258 //JCP settings dir 02/10/2009
259 const std::string settingsdirectory = GetUserSettingsDirectory();
260 //boost::algorithm::replace_all( mUserSettingsDirectory,
261 // INVALID_FILE_SEPARATOR ,
262 // VALID_FILE_SEPARATOR);
264 //("C:\\Documents and Settings\\cervenansky\\.gimmick\\"); // settingsdirectory );
266 isdir = boost::filesystem::is_directory(settingsdirectory); // settingsdirectory );
269 GimmickMessage(1,"Directory '"<<GetUserSettingsDirectory()<<"' "
270 << "does not exist : creating it"<<std::endl);
272 if ( ! boost::filesystem::create_directory( GetUserSettingsDirectory() ) )
274 GimmickError("ERROR CREATING '"<<GetUserSettingsDirectory()<<"'");
278 std::string setDir=GetUserSettingsDirectory();
279 boost::algorithm::replace_all( setDir,
280 INVALID_FILE_SEPARATOR ,
281 VALID_FILE_SEPARATOR);
283 boost::filesystem::create_directory( setDir );
284 setDir+="creaImageIO/";
285 boost::filesystem::create_directory( setDir );
286 setDir+=mLocalDescpName;
288 if(!boost::filesystem::is_regular(setDir))
291 crea::System::GetAppPath(name,PATH_MAX);
292 std::cout<<name<<std::endl;
294 std::string path=name;
295 path=path.substr(0,path.size()-1);
296 path=path.substr(0,path.find_last_of("/"));
297 //Creating directories
299 // The following stuff works on Linux, NOT CHECKED on Windows // JPR
302 path+="/bin/share/creaImageIO/";
306 path+="/../share/creaImageIO/";
308 #if defined(__APPLE__)
309 path+="/../../../../share/creaImageIO/";
313 path+= mLocalDescpName;
315 std::cout <<"From: " << path <<std::endl;
316 std::cout <<"To: " << setDir <<std::endl;
317 boost::algorithm::replace_all( path,
318 INVALID_FILE_SEPARATOR ,
319 VALID_FILE_SEPARATOR);
320 boost::filesystem::copy_file(path,setDir);
324 //========================================================================
327 //========================================================================
328 /// Sets message level
329 void Gimmick::SetMessageLevel(int l)
331 SetGimmickMessageLevel(l);
333 //========================================================================
335 //========================================================================
336 /// Sets message level
337 void Gimmick::SetDebugMessageLevel(int l)
339 SetGimmickDebugMessageLevel(l);
341 //========================================================================
343 //========================================================================
344 /// Returns the tree handler with the given name
345 TreeHandler* Gimmick::GetTreeHandler(const std::string& name) const
347 TreeHandlerMapType::const_iterator i;
348 i = GetTreeHandlerMap().find(name);
349 if ( i == GetTreeHandlerMap().end() )
351 GimmickError("TreeHandler '"<<name<<"' does not exist");
356 //========================================================================
357 /// Add the files to the tree handler
358 void Gimmick::AddFiles(const std::string& d,
359 const std::vector<std::string>& filenames)
361 GimmickMessage(2,"Adding files to '"<<d<<"'"<<std::endl);
362 mImageAdder.SetCurrentDatabase(d);
363 mImageAdder.SetTreeHandler(GetTreeHandler(d));
364 mImageAdder.SetSynchronizer(mSynchronizer);
365 mImageAdder.AddFiles(filenames);
367 //========================================================================
369 //========================================================================
370 /// Add a dir to the local database
371 void Gimmick::AddDir(const std::string& d, const std::string& f,
374 GimmickMessage(2,"Adding dir '"<<f<<"' to '"<<d<<"' recurse:" <<recurse<<std::endl);
375 TreeHandler * handler=GetTreeHandler(d);
376 mImageAdder.SetCurrentDatabase(d);
377 mImageAdder.SetTreeHandler(handler);
378 mImageAdder.SetSynchronizer(mSynchronizer);
379 mImageAdder.AddDirectory(f,recurse);
382 //========================================================================
384 //========================================================================
385 void Gimmick::RemoveFile(const std::string& d,
388 mImageAdder.SetCurrentDatabase(d);
389 mImageAdder.SetSynchronizer(mSynchronizer);
390 mImageAdder.RemoveFile(node);
392 //========================================================================
394 //void Gimmick::Anonymize(std::vector<std::string>i_files) { }
395 //========================================================================
397 void Gimmick::CopyFiles(const std::vector<std::string>& filenames, const std::string& d )
399 TreeHandler * handler=GetTreeHandler(d);
400 mImageAdder.SetCurrentDatabase(d);
401 mImageAdder.SetTreeHandler(handler);
402 mImageAdder.SetSynchronizer(mSynchronizer);
403 mImageAdder.CopyFiles(filenames, mSettings->getValue(SETTINGS_COPY_PATH));
406 //========================================================================
408 std::string Gimmick::Synchronize(const std::string& d, bool repair, bool checkAttributes)
410 TreeHandler * handler=GetTreeHandler(d);
411 mImageAdder.SetCurrentDatabase(d);
412 mImageAdder.SetTreeHandler(handler);
413 mImageAdder.SetSynchronizer(mSynchronizer);
414 return mImageAdder.Synchronize(repair, checkAttributes);
417 //========================================================================
419 void Gimmick::Print(const std::string& d)
421 GetTreeHandler(d)->GetTree().Print();
423 //========================================================================
425 void Gimmick::GetSetting(const std::string& name, std::string& value)
427 value = mSettings->getValue(name);
429 //========================================================================
431 //========================================================================
433 void Gimmick::GetAttributes(const std::string& d,
434 const std::string& filename,
435 const std::vector<std::string>& params,
436 std::vector<std::string>& results)
438 TreeHandler * handler=GetTreeHandler(d);
439 mImageAdder.SetCurrentDatabase(d);
440 mImageAdder.SetTreeHandler(handler);
441 mImageAdder.SetSynchronizer(mSynchronizer);
442 mImageAdder.GetAttributes(params, filename, results);
444 //========================================================================
446 //========================================================================
447 // get attributes values from database for a given file from database
448 //========================================================================
449 void Gimmick::GetAttributes(const std::string filename, std::map<std::string, std::string> &i_res, OutputAttr i_attr)
451 if (i_attr.inside.size() > 0)
453 std::map<std::string, std::string> map_attr;
454 TreeHandler * handler=GetTreeHandler(i_attr.db);
455 handler->getAllAttributes(filename, map_attr);
456 if(i_attr.inside.front() == "ALL") // we take all values
458 std::map<std::string, std::string>::iterator it = map_attr.begin();
459 for(; it != map_attr.end(); it++)
461 i_res[it->first] = it->second;
464 std::vector<std::string>::iterator it = i_attr.inside.begin();
465 for(; it != i_attr.inside.end(); it++)
467 i_res[(*it)] = map_attr[(*it)];
474 //========================================================================
476 void Gimmick::UpdateSetting(const std::string& name, const std::string& value)
478 mSettings->updateSetting(name,value);
479 mSettings->writeSettingsFile();
481 //========================================================================
483 void Gimmick::DeleteDrive(const std::string& drive)
485 for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
486 it!= mTreeHandlerMap.end();
489 mImageAdder.SetTreeHandler(it->second);
490 mImageAdder.DeleteDriveFromMainDB(drive);
492 mImageAdder.SetSynchronizer(mSynchronizer);
493 mImageAdder.DeleteDriveFromOtherDB(drive);
496 //========================================================================
497 void Gimmick::EditField(tree::Node* node, const std::string& d, const std::string& name, const std::string& key, const std::string& val)
499 TreeHandler * handler=GetTreeHandler(d);
500 mImageAdder.SetCurrentDatabase(d);
501 mImageAdder.SetTreeHandler(handler);
502 mImageAdder.EditField(node,name,key,val);
504 //========================================================================
506 ////////////////////////////////////////////////////////////////////////
507 // add DB from Settings file //
510 ////////////////////////////////////////////////////////////////////////
511 void Gimmick::addDBSettings()
514 std::string pathSettings = mSettings->getValue(SETTINGS_DBPATH);
516 // split to find all paths
517 std::vector<std::string> paths;
518 std::string separator = ";";
519 std::string::size_type last_pos = pathSettings.find_first_not_of(separator);
520 //find first separator
521 std::string::size_type pos = pathSettings.find_first_of(separator, last_pos);
522 while(std::string::npos != pos || std::string::npos != last_pos)
524 paths.push_back(pathSettings.substr(last_pos, pos - last_pos));
525 last_pos = pathSettings.find_first_not_of(separator, pos);
526 pos = pathSettings.find_first_of(separator, last_pos);
529 std::vector<std::string>::iterator it_path = paths.begin();
530 for(; it_path != paths.end(); ++it_path)
532 pos = it_path->find_last_of("\\");
533 last_pos = it_path->find_last_of(".");
534 std::string name = it_path->substr(pos +1, last_pos -pos-1 );
535 addDB(name, it_path->c_str());
540 ///////////////////////////////////////////////////////////////////////////////
541 // Fill attributes structure with attributes present in database (inside vector
542 // and not present (outside)
543 ///////////////////////////////////////////////////////////////////////////////
544 void Gimmick::fillVectInfos(std::vector<std::string> i_attr, OutputAttr &infos)
546 //test if a tag is present in Database descriptor
547 TreeHandler * handler=GetTreeHandler(infos.db);
548 mImageAdder.SetTreeHandler(handler);
549 std::vector<std::string>::const_iterator it = i_attr.begin();
550 for (;it != i_attr.end(); it++)
552 if( mImageAdder.isAttributeExist((*it)) != "" ) // in DB
554 printf("EED Gimmick::fillVectInfos inside %s\n",(*it).c_str());
555 infos.inside.push_back((*it));
557 infos.outside.push_back((*it)); // Need to scan again the files
558 printf("EED Gimmick::fillVectInfos outside %s\n",(*it).c_str());
563 const std::string Gimmick::getSummary()
565 const AddProgress& p = GetAddProgress();
566 std::stringstream mess;
567 mess << "Dirs \tscanned\t: " << p.GetNumberScannedDirs() << "\n";
568 mess << "Files\tscanned\t: " << p.GetNumberScannedFiles() << "\n";
569 mess << "Files\thandled\t: " << p.GetNumberHandledFiles() << "\n\n";
570 mess << "Files\tadded \t: " << p.GetNumberAddedFiles() << "\n\n";