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)
206 mHomeDirectory = getenv("USERPROFILE");
207 #elif defined(__GNUC__)
208 mHomeDirectory = getenv("HOME");
211 return mHomeDirectory;
213 //================================================================
214 const std::string& Gimmick::GetUserSettingsDirectory()
216 printf("EED Gimmick::GetUserSettingsDirectory() Start\n");
217 if (mUserSettingsDirectory.size()==0)
219 printf("EED Gimmick::GetUserSettingsDirectory() 1\n");
220 mUserSettingsDirectory = GetHomeDirectory();
221 printf("EED Gimmick::GetUserSettingsDirectory() 2 %s\n",mUserSettingsDirectory.c_str());
222 mUserSettingsDirectory += "/.creaImageIO/";
223 boost::algorithm::replace_all( mUserSettingsDirectory,
224 INVALID_FILE_SEPARATOR ,
225 VALID_FILE_SEPARATOR);
227 printf("EED Gimmick::GetUserSettingsDirectory() End\n");
228 return mUserSettingsDirectory;
230 //================================================================
233 //================================================================
234 const std::string& Gimmick::GetLocalDatabasePath()
236 if (mLocalDatabasePath.size()==0)
238 mLocalDatabasePath = GetUserSettingsDirectory();
239 mLocalDatabasePath += "share/creaImageIO/";
240 mLocalDatabasePath += mLocalDBName;
241 mLocalDatabasePath +=".sqlite3";
242 boost::algorithm::replace_all( mLocalDatabasePath,
243 INVALID_FILE_SEPARATOR ,
244 VALID_FILE_SEPARATOR);
246 return mLocalDatabasePath;
249 //========================================================================
251 //========================================================================
252 void Gimmick::CreateUserSettingsDirectory()
255 // std::string st("C:/Documents and Settings/cervenansky/.gimmick/");
256 // boost::algorithm::replace_all( st,
257 // INVALID_FILE_SEPARATOR ,
258 // VALID_FILE_SEPARATOR);
259 //const boost::filesystem::path mpath(st);
260 //C:\Documents and Settings\cervenansky\.gimmick");
261 //if ( !boost::filesystem::exists( path ) ) return ;
262 // boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
263 // for ( boost::filesystem::directory_iterator itr( path ); itr != end_itr; ++itr )
265 //// If is directory & recurse : do recurse
266 // if ( boost::filesystem::is_directory(itr->status()) )
270 //JCP settings dir 02/10/2009
271 const std::string settingsdirectory = GetUserSettingsDirectory();
272 //boost::algorithm::replace_all( mUserSettingsDirectory,
273 // INVALID_FILE_SEPARATOR ,
274 // VALID_FILE_SEPARATOR);
276 //("C:\\Documents and Settings\\cervenansky\\.gimmick\\"); // settingsdirectory );
278 isdir = boost::filesystem::is_directory(settingsdirectory); // settingsdirectory );
281 GimmickMessage(1,"Directory '"<<GetUserSettingsDirectory()<<"' "
282 << "does not exist : creating it"<<std::endl);
284 if ( ! boost::filesystem::create_directory( GetUserSettingsDirectory() ) )
286 GimmickError("ERROR CREATING '"<<GetUserSettingsDirectory()<<"'");
290 std::string setDir=GetUserSettingsDirectory();
291 boost::algorithm::replace_all( setDir,
292 INVALID_FILE_SEPARATOR ,
293 VALID_FILE_SEPARATOR);
295 boost::filesystem::create_directory( setDir );
296 setDir+="creaImageIO/";
297 boost::filesystem::create_directory( setDir );
298 setDir+=mLocalDescpName;
300 if(!boost::filesystem::is_regular(setDir))
303 crea::System::GetAppPath(name,PATH_MAX);
304 std::cout<<name<<std::endl;
306 std::string path=name;
307 path=path.substr(0,path.size()-1);
308 path=path.substr(0,path.find_last_of("/"));
309 //Creating directories
311 // The following stuff works on Linux, NOT CHECKED on Windows // JPR
314 path+="/bin/share/creaImageIO/";
318 path+="/../share/creaImageIO/";
320 #if defined(__APPLE__)
321 path+="/../../../../share/creaImageIO/";
325 path+= mLocalDescpName;
327 std::cout <<"From: " << path <<std::endl;
328 std::cout <<"To: " << setDir <<std::endl;
329 boost::algorithm::replace_all( path,
330 INVALID_FILE_SEPARATOR ,
331 VALID_FILE_SEPARATOR);
332 boost::filesystem::copy_file(path,setDir);
336 //========================================================================
339 //========================================================================
340 /// Sets message level
341 void Gimmick::SetMessageLevel(int l)
343 SetGimmickMessageLevel(l);
345 //========================================================================
347 //========================================================================
348 /// Sets message level
349 void Gimmick::SetDebugMessageLevel(int l)
351 SetGimmickDebugMessageLevel(l);
353 //========================================================================
355 //========================================================================
356 /// Returns the tree handler with the given name
357 TreeHandler* Gimmick::GetTreeHandler(const std::string& name) const
359 TreeHandlerMapType::const_iterator i;
360 i = GetTreeHandlerMap().find(name);
361 if ( i == GetTreeHandlerMap().end() )
363 GimmickError("TreeHandler '"<<name<<"' does not exist");
368 //========================================================================
369 /// Add the files to the tree handler
370 void Gimmick::AddFiles(const std::string& d,
371 const std::vector<std::string>& filenames)
373 GimmickMessage(2,"Adding files to '"<<d<<"'"<<std::endl);
375 mImageAdder.SetCurrentDatabase(d);
376 mImageAdder.SetTreeHandler(GetTreeHandler(d));
377 mImageAdder.SetSynchronizer(mSynchronizer);
378 mImageAdder.AddFiles(filenames);
380 //========================================================================
382 //========================================================================
383 /// Add a dir to the local database
384 void Gimmick::AddDir(const std::string& d, const std::string& f,
387 GimmickMessage(2,"Adding dir '"<<f<<"' to '"<<d<<"' recurse:"
388 <<recurse<<std::endl);
390 TreeHandler * handler=GetTreeHandler(d);
391 mImageAdder.SetCurrentDatabase(d);
392 mImageAdder.SetTreeHandler(handler);
393 mImageAdder.SetSynchronizer(mSynchronizer);
394 mImageAdder.AddDirectory(f,recurse);
397 //========================================================================
399 //========================================================================
400 void Gimmick::RemoveFile(const std::string& d,
403 mImageAdder.SetCurrentDatabase(d);
404 mImageAdder.SetSynchronizer(mSynchronizer);
405 mImageAdder.RemoveFile(node);
407 //========================================================================
409 //void Gimmick::Anonymize(std::vector<std::string>i_files) { }
410 //========================================================================
412 void Gimmick::CopyFiles(const std::vector<std::string>& filenames, const std::string& d )
414 TreeHandler * handler=GetTreeHandler(d);
415 mImageAdder.SetCurrentDatabase(d);
416 mImageAdder.SetTreeHandler(handler);
417 mImageAdder.SetSynchronizer(mSynchronizer);
418 mImageAdder.CopyFiles(filenames, mSettings->getValue(SETTINGS_COPY_PATH));
421 //========================================================================
423 std::string Gimmick::Synchronize(const std::string& d, bool repair, bool checkAttributes)
425 TreeHandler * handler=GetTreeHandler(d);
426 mImageAdder.SetCurrentDatabase(d);
427 mImageAdder.SetTreeHandler(handler);
428 mImageAdder.SetSynchronizer(mSynchronizer);
429 return mImageAdder.Synchronize(repair, checkAttributes);
432 //========================================================================
434 void Gimmick::Print(const std::string& d)
436 GetTreeHandler(d)->GetTree().Print();
438 //========================================================================
440 void Gimmick::GetSetting(const std::string& name, std::string& value)
442 value = mSettings->getValue(name);
444 //========================================================================
446 //========================================================================
448 void Gimmick::GetAttributes(const std::string& d,
449 const std::string& filename,
450 const std::vector<std::string>& params,
451 std::vector<std::string>& results)
453 TreeHandler * handler=GetTreeHandler(d);
454 mImageAdder.SetCurrentDatabase(d);
455 mImageAdder.SetTreeHandler(handler);
456 mImageAdder.SetSynchronizer(mSynchronizer);
457 mImageAdder.GetAttributes(params, filename, results);
459 //========================================================================
461 //========================================================================
462 // get attributes values from database for a given file from database
463 //========================================================================
464 void Gimmick::GetAttributes(const std::string filename, std::map<std::string, std::string> &i_res, OutputAttr i_attr)
466 if (i_attr.inside.size() > 0)
468 std::map<std::string, std::string> map_attr;
469 TreeHandler * handler=GetTreeHandler(i_attr.db);
470 handler->getAllAttributes(filename, map_attr);
471 if(i_attr.inside.front() == "ALL") // we take all values
473 std::map<std::string, std::string>::iterator it = map_attr.begin();
474 for(; it != map_attr.end(); it++)
475 i_res[it->first] = it->second;
479 std::vector<std::string>::iterator it = i_attr.inside.begin();
480 for(; it != i_attr.inside.end(); it++)
481 i_res[(*it)] = map_attr[(*it)];
487 //========================================================================
489 void Gimmick::UpdateSetting(const std::string& name, const std::string& value)
491 mSettings->updateSetting(name,value);
492 mSettings->writeSettingsFile();
494 //========================================================================
496 void Gimmick::DeleteDrive(const std::string& drive)
498 for( TreeHandlerMapType::const_iterator it = mTreeHandlerMap.begin();
499 it!= mTreeHandlerMap.end();
502 mImageAdder.SetTreeHandler(it->second);
503 mImageAdder.DeleteDriveFromMainDB(drive);
505 mImageAdder.SetSynchronizer(mSynchronizer);
506 mImageAdder.DeleteDriveFromOtherDB(drive);
509 //========================================================================
510 void Gimmick::EditField(tree::Node* node, const std::string& d, const std::string& name, const std::string& key, const std::string& val)
512 TreeHandler * handler=GetTreeHandler(d);
513 mImageAdder.SetCurrentDatabase(d);
514 mImageAdder.SetTreeHandler(handler);
515 mImageAdder.EditField(node,name,key,val);
517 //========================================================================
519 ////////////////////////////////////////////////////////////////////////
520 // add DB from Settings file //
523 ////////////////////////////////////////////////////////////////////////
524 void Gimmick::addDBSettings()
527 std::string pathSettings = mSettings->getValue(SETTINGS_DBPATH);
529 // split to find all paths
530 std::vector<std::string> paths;
531 std::string separator = ";";
532 std::string::size_type last_pos = pathSettings.find_first_not_of(separator);
533 //find first separator
534 std::string::size_type pos = pathSettings.find_first_of(separator, last_pos);
535 while(std::string::npos != pos || std::string::npos != last_pos)
537 paths.push_back(pathSettings.substr(last_pos, pos - last_pos));
538 last_pos = pathSettings.find_first_not_of(separator, pos);
539 pos = pathSettings.find_first_of(separator, last_pos);
542 std::vector<std::string>::iterator it_path = paths.begin();
543 for(; it_path != paths.end(); ++it_path)
545 pos = it_path->find_last_of("\\");
546 last_pos = it_path->find_last_of(".");
547 std::string name = it_path->substr(pos +1, last_pos -pos-1 );
548 addDB(name, it_path->c_str());
553 ///////////////////////////////////////////////////////////////////////////////
554 // Fill attributes structure with attributes present in database (inside vector
555 // and not present (outside)
556 ///////////////////////////////////////////////////////////////////////////////
557 void Gimmick::fillVectInfos(std::vector<std::string> i_attr, OutputAttr &infos)
559 //test if a tag is present in Database descriptor
560 TreeHandler * handler=GetTreeHandler(infos.db);
561 mImageAdder.SetTreeHandler(handler);
562 std::vector<std::string>::const_iterator it = i_attr.begin();
563 for (;it != i_attr.end(); it++)
565 if( mImageAdder.isAttributeExist((*it)) != "" ) // in DB
567 infos.inside.push_back((*it));
571 infos.outside.push_back((*it)); // Need to scan again the files
576 const std::string Gimmick::getSummary()
578 const AddProgress& p = GetAddProgress();
579 std::stringstream mess;
580 mess << "Dirs \tscanned\t: " << p.GetNumberScannedDirs() << "\n";
581 mess << "Files\tscanned\t: " << p.GetNumberScannedFiles() << "\n";
582 mess << "Files\thandled\t: " << p.GetNumberHandledFiles() << "\n\n";
583 mess << "Files\tadded \t: " << p.GetNumberAddedFiles() << "\n\n";