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 /*=========================================================================
30 Module: $RCSfile: bbtkUtilities.cxx,v $
32 Date: $Date: 2012/11/16 08:49:01 $
33 Version: $Revision: 1.15 $
34 =========================================================================*/
39 #include "bbtkUtilities.h"
40 #include "bbtkMessageManager.h"
47 #if defined(MACOSX) // assume this is OSX
48 # include <sys/param.h>
49 # include <mach-o/dyld.h> // _NSGetExecutablePath : must add -framework CoreFoundation to link line
52 # define PATH_MAX MAXPATHLEN
56 #ifndef PATH_MAX // If not defined yet : do it
57 # define PATH_MAX 2048
65 // ======================================================================
66 // See : http://www.techbytes.ca/techbyte103.html for more O.S.
67 bool Utilities::FileExists(std::string strFilename)
69 struct stat stFileInfo;
73 // Attempt to get the file attributes
74 intStat = stat(strFilename.c_str(),&stFileInfo);
77 // We were able to get the file attributes
78 // so the file obviously exists.
83 // We were not able to get the file attributes.
84 // This may mean that we don't have permission to
85 // access the folder which contains this file. If you
86 // need to do that level of checking, lookup the
87 // return values of stat which will give you
88 // more details on why stat failed.
96 // =====================================================================
98 std::string Utilities::ExtractPackageName(const std::string &name,
104 std::string::size_type slash_position = name.find_last_of("/\\");
105 if (slash_position != std::string::npos)
107 pkgname = name.substr(slash_position+1,std::string::npos);
108 path = name.substr(0,slash_position);
109 // std::cout << "F:P='"<<path<<"'"<<std::endl;//+1,std::string::npos);
116 // remove {.so | dll} if any
117 std::string::size_type dot_position = pkgname.find_last_of('.');
118 if (dot_position != std::string::npos){
119 pkgname = pkgname.substr(0,dot_position);
121 #if defined(__GNUC__)
124 // shared lib name = libbb<name>.so
126 // remove {libbb} if any
127 if (memcmp ( pkgname.c_str(), "libbb", 5) == 0) {
128 pkgname = pkgname.substr(5, pkgname.length());
131 /// \ \todo what would happen if (stupid) user names his package 'libbb' ?!?
132 /// \ --> Should be forbidden!
134 #elif defined(_WIN32)
137 // shared lib name = <name>.dll
139 // EED Problem loading package call bbtkTools
140 // // remove {bb} if any
141 if (memcmp (pkgname.c_str(), "bb", 2) == 0) {
142 pkgname = pkgname.substr(2, pkgname.length());
146 /// \ \todo what would happen if (stupid) user names his package 'bb' ?!?
147 /// \ --> Should be forbidden!
150 bbtkError("neither __GNUC__ nor _WIN32 ?!? How did you compile ?");
155 //=====================================================================
156 std::string Utilities::ExtractScriptName(const std::string &name,
161 std::string::size_type slash_position = name.find_last_of("/\\");
162 if (slash_position != std::string::npos) {
163 pkgname =name.substr(slash_position+1,std::string::npos);
164 path = name.substr(0,slash_position);
168 // remove {.bbs } if any
169 std::string::size_type dot_position = pkgname.find_last_of('.');
170 if (dot_position != std::string::npos){
171 pkgname = pkgname.substr(0,dot_position);
176 // ========================================================================
178 std::string Utilities::ExpandLibName(const std::string &name, bool verbose)
180 // ----- Think of expanding path name ( ./ ../ ../../ )
182 char buf[2048]; // for getcwd
183 char * currentDir = getcwd(buf, 2048);
184 std::string cwd(currentDir);
185 std::string libname(name);
186 std::string fileSeparator;
187 fileSeparator = ConfigurationFile::GetInstance().Get_file_separator();
188 // tooHigh : true is user supplies a library pathname with too many "../"
189 bool tooHigh = false;
191 //std::cout << "------------------cwd [" << cwd << "] name [" << name << "]" << std::endl;
193 if ( name[0] == '/' || name[1] == ':' ) // Linux or Windows absolute name
197 else if ( name =="." )
199 libname = cwd + fileSeparator;
202 else if (name[0] == '.' && (name[1] == '/' || name[1] == '\\') )
204 libname = cwd + fileSeparator + name.substr(2, name.length());
207 else if ( name[0] == '.' && name[1] == '.' /* && (name[2] == '/' || name[2] == '\\') */ )
209 if ( IsAtRoot(cwd) ) // hope it gets / (for Linux), C: D: (for Windows)
211 // if we are already at / or c: --> hopeless
213 std::cout << " File path [" << name << "] doesn't exist" << std::endl;
218 // iterate on ../ and go up from the current working dir!
220 bool alreadyProcessRoot = false;
222 //if (a[a.size()-1] != fileSeparator[0])
223 // a.append(fileSeparator);
224 //std::cout << "------------------a [" << a << "]" << std::endl;
226 for(;;) // wild loop !
228 std::string::size_type slash_position = cwd.find_last_of(fileSeparator);
229 if (slash_position != std::string::npos) {
230 if (slash_position == 0)
232 cwd = cwd.substr(0,slash_position/*+1*/);
233 //std::cout << "------------------cwd [" << cwd << "]" << std::endl;
239 a = a.substr(3, /*name.length()*/ a.length()); // remove ../
240 //std::cout << "------------------a [" << a << "]" << std::endl;
241 if (a == "" || alreadyProcessRoot)
244 std::cout << " File path : [" << name << "] doesn't exist" << std::endl;
248 // std::string b = cwd + a;
250 char c = cwd[cwd.size()-1];
251 if (c != '/' && c != '\\' )
252 libname += fileSeparator;
255 if ( a[0] != '.' ) // if . (probabely ../), loop again
259 alreadyProcessRoot = true;
261 } // end iterating on ../
263 //std::cout << "------------------out of loop]" << std::endl;
268 } // ----- End of expanding path name ( ./ ../ ../../ )
270 std::cout <<"* ERROR in ExpandLibName : should never get here!" << std::endl;
272 return(""); // Will never get here!
275 // ===================================================================================
277 std::string Utilities::MakeLibnameFromPath(std::string path, std::string pkgname)
279 std::string libname = path;
281 char c = path[path.size()-1];
282 #if defined(__GNUC__)
290 #elif defined(WIN32) // mingw
296 #elif defined(_WIN32)
309 // ===================================================================================
311 std::string Utilities::MakePkgnameFromPath(std::string path, std::string pkgname, bool addExt)
313 std::string libname = path;
315 char c = path[path.size()-1];
316 if (c != '/' && c != '\\')
318 libname += ConfigurationFile::GetInstance().Get_file_separator ();
323 int l = libname.size();
326 if (libname.substr(l-4, 4) != ".bbs")
328 libname = libname + ".bbs";
336 // =======================================================================
338 // =======================================================================
339 /// Returns the user settings dir, e.g. /home/username/.bbtk
340 std::string Utilities::GetUserSettingsDir()
342 std::string str_Home=Utilities::GetEnvHome();
343 std::string fullname = str_Home + "/.bbtk";
344 MakeValidFileName(fullname);
349 // =======================================================================
350 /// Builds the complete path to the file 'name' located
351 /// in user settings dir, e.g. /home/username/.bbtk/
352 std::string Utilities::MakeUserSettingsFullFileName(const std::string& name)
354 std::string str_home=Utilities::GetEnvHome();
355 std::string fullname = str_home + "/.bbtk/" + name;
356 MakeValidFileName(fullname);
359 // =======================================================================
362 // =======================================================================
363 void Utilities::CreateDirectoryIfNeeded( std::string const &dirName)
365 if (FileExists(dirName)) return;
366 std::string cmd("mkdir \"");
371 // =======================================================================
374 //========================================================================
375 bool Utilities::IsAtRoot(std::string cwd)
377 if ( cwd == "/" // hope it gets / (for Linux)
378 || (cwd.size() <= 3 && cwd[1] == ':') ) // hope it gets C: D: (for Windows)
383 // ======================================================================
385 // ======================================================================
386 bool Utilities::IsDirectory(std::string const &dirName)
390 if ( stat(dirName.c_str(), &fs) == 0 )
393 return ((fs.st_mode & _S_IFDIR) != 0);
395 return S_ISDIR(fs.st_mode);
403 // =======================================================================
405 // =======================================================================
406 void Utilities::SplitAroundFirstDot( const std::string& in,
410 std::string delimiter = ".";
411 std::string::size_type pos = in.find_first_of(delimiter);
412 if (std::string::npos != pos)
414 left = in.substr(0,pos);
415 right = in.substr(pos+1,in.size());
422 bbtkGlobalError("Token '"<<in<<"' : expected 'a.b' format but no dot found");
425 //=======================================================================
427 //=======================================================================
428 void Utilities::SplitString ( const std::string& str,
429 const std::string& delimiters,
430 std::vector<std::string>& tokens)
432 // Skip delimiters at beginning.
433 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
434 // Find first delimiter.
435 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
437 while (std::string::npos != pos || std::string::npos != lastPos)
439 // Found a token, add it to the vector.
440 tokens.push_back(str.substr(lastPos, pos - lastPos));
441 // Skip delimiters. Note the "not_of"
442 lastPos = str.find_first_not_of(delimiters, pos);
443 // Find next delimiter
444 pos = str.find_first_of(delimiters, lastPos);
448 //=======================================================================
451 // ======================================================================
452 std::string Utilities::get_file_name(const std::string& s)
454 std::string::size_type slash_position = s.find_last_of("/\\");
455 if (slash_position != std::string::npos)
457 return s.substr(slash_position+1,std::string::npos);
464 //=======================================================================
467 // ========================================================================
469 * \brief Explore a directory with possibility of recursion
470 * return number of files read
471 * @param dirpath directory to explore
472 * @param recursive whether we want recursion or not
474 int Utilities::Explore(std::string const &dirpath, bool recursive, std::vector<std::string> &Filenames)
476 int numberOfFiles = 0;
477 std::string fileName;
479 std::string dirName = dirpath;
482 WIN32_FIND_DATA fileData;
483 HANDLE hFile = FindFirstFile((dirName+"\\*").c_str(), &fileData);
485 for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
486 b = FindNextFile(hFile, &fileData))
488 fileName = fileData.cFileName;
489 if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
491 // Need to check for . and .. to avoid infinite loop
492 if ( fileName != "." && fileName != ".." && recursive )
494 numberOfFiles += Explore(dirName+ "\\"+fileName,recursive,Filenames);
499 Filenames.push_back(dirName+"\\"+fileName);
503 DWORD dwError = GetLastError();
504 if (hFile != INVALID_HANDLE_VALUE)
506 if (dwError != ERROR_NO_MORE_FILES)
509 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
510 FORMAT_MESSAGE_FROM_SYSTEM|
511 FORMAT_MESSAGE_IGNORE_INSERTS,
513 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
514 (LPTSTR) &lpMsgBuf,0,NULL);
516 // ErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
517 // <<" for the directory : "<<dirName);
523 // Real POSIX implementation: scandir is a BSD extension only, and doesn't
524 // work on debian for example
525 //std::cout <<"in Explor dirname[" << dirName << "]" << std::endl;
526 DIR* dir = opendir(dirName.c_str());
531 //std::cout <<"Open OK" << std::endl;
532 // According to POSIX, the dirent structure contains a field char d_name[]
533 // of unspecified size, with at most NAME_MAX characters preceeding the
534 // terminating null character. Use of other fields will harm the porta-
535 // bility of your programs.
539 for (d = readdir(dir); d; d = readdir(dir))
541 fileName = dirName + "/" + d->d_name;
542 //std::cout <<"in Explor filename[" << fileName << "]" << std::endl;
543 if( stat(fileName.c_str(), &buf) != 0 )
545 //ErrorMacro( strerror(errno) );
547 if ( S_ISREG(buf.st_mode) ) //is it a regular file?
549 Filenames.push_back( fileName );
552 else if ( S_ISDIR(buf.st_mode) ) //directory?
554 if ( d->d_name[0] != '.' && recursive ) //we also skip hidden files
556 numberOfFiles += Explore( fileName, recursive, Filenames);
561 //ErrorMacro( "Unexpected error" );
565 if( closedir(dir) != 0 )
567 // ErrorMacro( strerror(errno) );
571 return numberOfFiles;
574 //=======================================================================
577 //=======================================================================
578 // Replaces substrings "\\n" by a real carriage return "\n"
579 void Utilities::SubsBackslashN ( std::string& s )
581 std::string ss("\\n");
582 std::string::size_type pos = 0;
584 const char* cr = "\n";
585 while ( pos != std::string::npos )
587 s.replace(pos,2,cr,1);
588 pos = s.find(ss, pos-1);
591 //=======================================================================
594 //=======================================================================
596 bool Utilities::loosematch(std::string stdLine,std::string stdOptions)
599 std::vector<std::string> tokens;
600 SplitString ( stdOptions,"|", tokens);
601 int i,size=tokens.size();
602 for (i=0; i<size; i++)
605 if ( strcmpi(stdLine.c_str(),tokens[i].c_str())==0)
610 if ( strcasecmp(stdLine.c_str(),tokens[i].c_str())==0)
619 //=========================================================================
621 //=========================================================================
622 // From http://www.fltk.org/newsgroups.php?gfltk.general+v:22083
624 int get_app_path (char *pname, size_t pathsize)
628 /* Oddly, the readlink(2) man page says no NULL is appended. */
629 /* So you have to do it yourself, based on the return value: */
630 pathsize --; /* Preserve a space to add the trailing NULL */
631 long result = readlink("/proc/self/exe", pname, pathsize);
634 pname[result] = 0; /* add the #@!%ing NULL */
636 if ((access(pname, 0) == 0))
637 return 0; /* file exists, return OK */
638 /*else name doesn't seem to exist, return FAIL (falls
647 long result = GetModuleFileName(NULL, pname2, pathsize);
648 int ret = wcstombs ( pname, pname2, sizeof(pname) );
649 // long result = GetModuleFileName(NULL, pname, pathsize);
652 /* fix up the dir slashes... */
653 int len = strlen(pname);
655 for (idx = 0; idx < len; idx++)
657 if (pname[idx] == '\\') pname[idx] = '/';
660 for (idx = len-1; idx >=0 ; idx--)
662 if (pname[idx] == '/')
669 if ((access(pname, 0) == 0))
670 return 0; /* file exists, return OK */
671 /*else name doesn't seem to exist, return FAIL (falls
677 char *p = getexecname();
680 /* According to the Sun manpages, getexecname will
681 "normally" return an */
682 /* absolute path - BUT might not... AND that IF it is not,
684 /* getcwd() will "usually" be the correct thing... Urgh!
687 /* check pathname is absolute (begins with a / ???) */
688 if (p[0] == '/') /* assume this means we have an
691 strncpy(pname, p, pathsize);
692 if ((access(pname, 0) == 0))
693 return 0; /* file exists, return OK */
695 else /* if not, prepend getcwd() then check if file
698 getcwd(pname, pathsize);
699 long result = strlen(pname);
700 strncat(pname, "/", (pathsize - result));
702 strncat(pname, p, (pathsize - result));
704 if ((access(pname, 0) == 0))
705 return 0; /* file exists, return OK */
706 /*else name doesn't seem to exist, return FAIL
712 #ifdef MACOSX /* assume this is OSX */
714 from http://www.hmug.org/man/3/NSModule.html
716 extern int _NSGetExecutablePath(char *buf, unsigned long
719 _NSGetExecutablePath copies the path of the executable
720 into the buffer and returns 0 if the path was successfully
721 copied in the provided buffer. If the buffer is not large
722 enough, -1 is returned and the expected buffer size is
723 copied in *bufsize. Note that _NSGetExecutablePath will
724 return "a path" to the executable not a "real path" to the
725 executable. That is the path may be a symbolic link and
726 not the real file. And with deep directories the total
727 bufsize needed could be more than MAXPATHLEN.
730 char *given_path = (char*)malloc(MAXPATHLEN * 2);
731 if (!given_path) return status;
733 uint32_t npathsize = MAXPATHLEN * 2;
734 long result = _NSGetExecutablePath(given_path, &npathsize);
736 { /* OK, we got something - now try and resolve the real path...
738 if (realpath(given_path, pname) != NULL)
740 if ((access(pname, 0) == 0))
741 status = 0; /* file exists, return OK */
749 return -1; /* Path Lookup Failed */
751 //=========================================================================
755 //=========================================================================
756 std::string Utilities::GetExecutablePath()
759 int err = get_app_path(name, PATH_MAX);
764 bbtkGlobalError("Could not determine current executable path ?");
766 catch (bbtk::Exception e)
768 std::cerr << e.GetErrorMessage() << std::endl;
772 // remove the exe name
774 slash = strrchr(name, VALID_FILE_SEPARATOR_CHAR);
781 //=========================================================================
784 std::string Utilities::GetEnvHome()
786 #if defined(__GNUC__)
788 char *envHome=getenv("HOME");
793 strHome = "/var/www/testwtdbg/docroot";
795 #elif defined(_WIN32)
796 std::string strHome( getenv("USERPROFILE") );
806 //---------NodeTree---------------
808 NodeTreeC::NodeTreeC()
813 NodeTreeC::NodeTreeC(std::string _data)
818 NodeTreeC::~NodeTreeC()
822 void NodeTreeC::deleteTree()
825 std::cout<<"NodeTreeC::deleteTree 1"<<std::endl;
826 childs.erase(childs.begin(),childs.begin()+childs.size());
827 std::cout<<"NodeTreeC::deleteTree 2"<<std::endl;
830 void NodeTreeC::insertChild(std::string _data)
832 NodeTreeC temp = NodeTreeC(_data);
833 childs.push_back(temp);
834 //std::cout<<"NodeTreeC::insertChild"<<std::endl;
837 void NodeTreeC::treeTour(int lvl)
839 std::string space = "";
840 for (int j=0; j<lvl ; j++){
844 std::cout <<space<<"data: "<< data << " size: "<< childs.size() << std::endl;
845 for(int i = 0 ; i < childs.size(); i++)
847 childs[i].treeTour(lvl);
851 void NodeTreeC::setData(std::string _data)
854 //std::cout<<"NodeTreeC::setData"<<std::endl;