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"
42 #if defined(MACOSX) // assume this is OSX
43 # include <sys/param.h>
44 # include <mach-o/dyld.h> // _NSGetExecutablePath : must add -framework CoreFoundation to link line
47 # define PATH_MAX MAXPATHLEN
51 #ifndef PATH_MAX // If not defined yet : do it
52 # define PATH_MAX 2048
60 // ======================================================================
61 // See : http://www.techbytes.ca/techbyte103.html for more O.S.
62 bool Utilities::FileExists(std::string strFilename)
64 struct stat stFileInfo;
68 // Attempt to get the file attributes
69 intStat = stat(strFilename.c_str(),&stFileInfo);
72 // We were able to get the file attributes
73 // so the file obviously exists.
78 // We were not able to get the file attributes.
79 // This may mean that we don't have permission to
80 // access the folder which contains this file. If you
81 // need to do that level of checking, lookup the
82 // return values of stat which will give you
83 // more details on why stat failed.
91 // =====================================================================
93 std::string Utilities::ExtractPackageName(const std::string &name,
99 std::string::size_type slash_position = name.find_last_of("/\\");
100 if (slash_position != std::string::npos)
102 pkgname = name.substr(slash_position+1,std::string::npos);
103 path = name.substr(0,slash_position);
104 // std::cout << "F:P='"<<path<<"'"<<std::endl;//+1,std::string::npos);
111 // remove {.so | dll} if any
112 std::string::size_type dot_position = pkgname.find_last_of('.');
113 if (dot_position != std::string::npos){
114 pkgname = pkgname.substr(0,dot_position);
116 #if defined(__GNUC__)
119 // shared lib name = libbb<name>.so
121 // remove {libbb} if any
122 if (memcmp ( pkgname.c_str(), "libbb", 5) == 0) {
123 pkgname = pkgname.substr(5, pkgname.length());
126 /// \ \todo what would happen if (stupid) user names his package 'libbb' ?!?
127 /// \ --> Should be forbidden!
129 #elif defined(_WIN32)
132 // shared lib name = <name>.dll
134 // EED Problem loading package call bbtkTools
135 // // remove {bb} if any
136 if (memcmp (pkgname.c_str(), "bb", 2) == 0) {
137 pkgname = pkgname.substr(2, pkgname.length());
141 /// \ \todo what would happen if (stupid) user names his package 'bb' ?!?
142 /// \ --> Should be forbidden!
145 bbtkError("neither __GNUC__ nor _WIN32 ?!? How did you compile ?");
150 //=====================================================================
151 std::string Utilities::ExtractScriptName(const std::string &name,
156 std::string::size_type slash_position = name.find_last_of("/\\");
157 if (slash_position != std::string::npos) {
158 pkgname =name.substr(slash_position+1,std::string::npos);
159 path = name.substr(0,slash_position);
163 // remove {.bbs } if any
164 std::string::size_type dot_position = pkgname.find_last_of('.');
165 if (dot_position != std::string::npos){
166 pkgname = pkgname.substr(0,dot_position);
171 // ========================================================================
173 std::string Utilities::ExpandLibName(const std::string &name, bool verbose)
175 // ----- Think of expanding path name ( ./ ../ ../../ )
177 char buf[2048]; // for getcwd
178 char * currentDir = getcwd(buf, 2048);
179 std::string cwd(currentDir);
180 std::string libname(name);
181 std::string fileSeparator;
182 fileSeparator = ConfigurationFile::GetInstance().Get_file_separator();
183 // tooHigh : true is user supplies a library pathname with too many "../"
184 bool tooHigh = false;
186 //std::cout << "------------------cwd [" << cwd << "] name [" << name << "]" << std::endl;
188 if ( name[0] == '/' || name[1] == ':' ) // Linux or Windows absolute name
192 else if ( name =="." )
194 libname = cwd + fileSeparator;
197 else if (name[0] == '.' && (name[1] == '/' || name[1] == '\\') )
199 libname = cwd + fileSeparator + name.substr(2, name.length());
202 else if ( name[0] == '.' && name[1] == '.' /* && (name[2] == '/' || name[2] == '\\') */ )
204 if ( IsAtRoot(cwd) ) // hope it gets / (for Linux), C: D: (for Windows)
206 // if we are already at / or c: --> hopeless
208 std::cout << " File path [" << name << "] doesn't exist" << std::endl;
213 // iterate on ../ and go up from the current working dir!
215 bool alreadyProcessRoot = false;
217 //if (a[a.size()-1] != fileSeparator[0])
218 // a.append(fileSeparator);
219 //std::cout << "------------------a [" << a << "]" << std::endl;
221 for(;;) // wild loop !
223 std::string::size_type slash_position = cwd.find_last_of(fileSeparator);
224 if (slash_position != std::string::npos) {
225 if (slash_position == 0)
227 cwd = cwd.substr(0,slash_position/*+1*/);
228 //std::cout << "------------------cwd [" << cwd << "]" << std::endl;
234 a = a.substr(3, /*name.length()*/ a.length()); // remove ../
235 //std::cout << "------------------a [" << a << "]" << std::endl;
236 if (a == "" || alreadyProcessRoot)
239 std::cout << " File path : [" << name << "] doesn't exist" << std::endl;
243 // std::string b = cwd + a;
245 char c = cwd[cwd.size()-1];
246 if (c != '/' && c != '\\' )
247 libname += fileSeparator;
250 if ( a[0] != '.' ) // if . (probabely ../), loop again
254 alreadyProcessRoot = true;
256 } // end iterating on ../
258 //std::cout << "------------------out of loop]" << std::endl;
263 } // ----- End of expanding path name ( ./ ../ ../../ )
265 std::cout <<"* ERROR in ExpandLibName : should never get here!" << std::endl;
267 return(""); // Will never get here!
270 // ===================================================================================
272 std::string Utilities::MakeLibnameFromPath(std::string path, std::string pkgname)
274 std::string libname = path;
276 char c = path[path.size()-1];
277 #if defined(__GNUC__)
289 #elif defined(_WIN32)
302 // ===================================================================================
304 std::string Utilities::MakePkgnameFromPath(std::string path, std::string pkgname, bool addExt)
306 std::string libname = path;
308 char c = path[path.size()-1];
309 if (c != '/' && c != '\\')
311 libname += ConfigurationFile::GetInstance().Get_file_separator ();
316 int l = libname.size();
319 if (libname.substr(l-4, 4) != ".bbs")
321 libname = libname + ".bbs";
329 // =======================================================================
331 // =======================================================================
332 /// Returns the user settings dir, e.g. /home/username/.bbtk
333 std::string Utilities::GetUserSettingsDir()
335 #if defined(__GNUC__)
336 std::string str_home(getenv("HOME"));
337 #elif defined(_WIN32)
338 std::string str_home(getenv("USERPROFILE"));
340 std::string fullname = str_home + "/.bbtk";
341 MakeValidFileName(fullname);
346 // =======================================================================
347 /// Builds the complete path to the file 'name' located
348 /// in user settings dir, e.g. /home/username/.bbtk/
349 std::string Utilities::MakeUserSettingsFullFileName(const std::string& name)
351 #if defined(__GNUC__)
352 std::string str_home(getenv("HOME"));
353 #elif defined(_WIN32)
354 std::string str_home(getenv("USERPROFILE"));
356 std::string fullname = str_home + "/.bbtk/" + name;
357 MakeValidFileName(fullname);
360 // =======================================================================
363 // =======================================================================
364 void Utilities::CreateDirectoryIfNeeded( std::string const &dirName)
366 if (FileExists(dirName)) return;
367 std::string cmd("mkdir \"");
372 // =======================================================================
375 //========================================================================
376 bool Utilities::IsAtRoot(std::string cwd)
378 if ( cwd == "/" // hope it gets / (for Linux)
379 || (cwd.size() <= 3 && cwd[1] == ':') ) // hope it gets C: D: (for Windows)
384 // ======================================================================
386 // ======================================================================
387 bool Utilities::IsDirectory(std::string const &dirName)
391 if ( stat(dirName.c_str(), &fs) == 0 )
394 return ((fs.st_mode & _S_IFDIR) != 0);
396 return S_ISDIR(fs.st_mode);
404 // =======================================================================
406 // =======================================================================
407 void Utilities::SplitAroundFirstDot( const std::string& in,
411 std::string delimiter = ".";
412 std::string::size_type pos = in.find_first_of(delimiter);
413 if (std::string::npos != pos)
415 left = in.substr(0,pos);
416 right = in.substr(pos+1,in.size());
423 bbtkGlobalError("Token '"<<in<<"' : expected 'a.b' format but no dot found");
426 //=======================================================================
428 //=======================================================================
429 void Utilities::SplitString ( const std::string& str,
430 const std::string& delimiters,
431 std::vector<std::string>& tokens)
433 // Skip delimiters at beginning.
434 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
435 // Find first delimiter.
436 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
438 while (std::string::npos != pos || std::string::npos != lastPos)
440 // Found a token, add it to the vector.
441 tokens.push_back(str.substr(lastPos, pos - lastPos));
442 // Skip delimiters. Note the "not_of"
443 lastPos = str.find_first_not_of(delimiters, pos);
444 // Find next delimiter
445 pos = str.find_first_of(delimiters, lastPos);
449 //=======================================================================
452 // ======================================================================
453 std::string Utilities::get_file_name(const std::string& s)
455 std::string::size_type slash_position = s.find_last_of("/\\");
456 if (slash_position != std::string::npos)
458 return s.substr(slash_position+1,std::string::npos);
465 //=======================================================================
468 // ========================================================================
470 * \brief Explore a directory with possibility of recursion
471 * return number of files read
472 * @param dirpath directory to explore
473 * @param recursive whether we want recursion or not
475 int Utilities::Explore(std::string const &dirpath, bool recursive, std::vector<std::string> &Filenames)
477 int numberOfFiles = 0;
478 std::string fileName;
480 std::string dirName = dirpath;
483 WIN32_FIND_DATA fileData;
484 HANDLE hFile = FindFirstFile((dirName+"\\*").c_str(), &fileData);
486 for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
487 b = FindNextFile(hFile, &fileData))
489 fileName = fileData.cFileName;
490 if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
492 // Need to check for . and .. to avoid infinite loop
493 if ( fileName != "." && fileName != ".." && recursive )
495 numberOfFiles += Explore(dirName+ "\\"+fileName,recursive,Filenames);
500 Filenames.push_back(dirName+"\\"+fileName);
504 DWORD dwError = GetLastError();
505 if (hFile != INVALID_HANDLE_VALUE)
507 if (dwError != ERROR_NO_MORE_FILES)
510 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
511 FORMAT_MESSAGE_FROM_SYSTEM|
512 FORMAT_MESSAGE_IGNORE_INSERTS,
514 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
515 (LPTSTR) &lpMsgBuf,0,NULL);
517 // ErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
518 // <<" for the directory : "<<dirName);
524 // Real POSIX implementation: scandir is a BSD extension only, and doesn't
525 // work on debian for example
526 //std::cout <<"in Explor dirname[" << dirName << "]" << std::endl;
527 DIR* dir = opendir(dirName.c_str());
532 //std::cout <<"Open OK" << std::endl;
533 // According to POSIX, the dirent structure contains a field char d_name[]
534 // of unspecified size, with at most NAME_MAX characters preceeding the
535 // terminating null character. Use of other fields will harm the porta-
536 // bility of your programs.
540 for (d = readdir(dir); d; d = readdir(dir))
542 fileName = dirName + "/" + d->d_name;
543 //std::cout <<"in Explor filename[" << fileName << "]" << std::endl;
544 if( stat(fileName.c_str(), &buf) != 0 )
546 //ErrorMacro( strerror(errno) );
548 if ( S_ISREG(buf.st_mode) ) //is it a regular file?
550 Filenames.push_back( fileName );
553 else if ( S_ISDIR(buf.st_mode) ) //directory?
555 if ( d->d_name[0] != '.' && recursive ) //we also skip hidden files
557 numberOfFiles += Explore( fileName, recursive, Filenames);
562 //ErrorMacro( "Unexpected error" );
566 if( closedir(dir) != 0 )
568 // ErrorMacro( strerror(errno) );
572 return numberOfFiles;
575 //=======================================================================
578 //=======================================================================
579 // Replaces substrings "\\n" by a real carriage return "\n"
580 void Utilities::SubsBackslashN ( std::string& s )
582 std::string ss("\\n");
583 std::string::size_type pos = 0;
585 const char* cr = "\n";
586 while ( pos != std::string::npos )
588 s.replace(pos,2,cr,1);
589 pos = s.find(ss, pos-1);
592 //=======================================================================
595 //=======================================================================
597 bool Utilities::loosematch(std::string stdLine,std::string stdOptions)
600 std::vector<std::string> tokens;
601 SplitString ( stdOptions,"|", tokens);
602 int i,size=tokens.size();
603 for (i=0; i<size; i++)
606 if ( strcmpi(stdLine.c_str(),tokens[i].c_str())==0)
611 if ( strcasecmp(stdLine.c_str(),tokens[i].c_str())==0)
620 //=========================================================================
622 //=========================================================================
623 // From http://www.fltk.org/newsgroups.php?gfltk.general+v:22083
625 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
644 long result = GetModuleFileName(NULL, pname, pathsize);
647 /* fix up the dir slashes... */
648 int len = strlen(pname);
650 for (idx = 0; idx < len; idx++)
652 if (pname[idx] == '\\') pname[idx] = '/';
655 for (idx = len-1; idx >=0 ; idx--)
657 if (pname[idx] == '/')
664 if ((access(pname, 0) == 0))
665 return 0; /* file exists, return OK */
666 /*else name doesn't seem to exist, return FAIL (falls
672 char *p = getexecname();
675 /* According to the Sun manpages, getexecname will
676 "normally" return an */
677 /* absolute path - BUT might not... AND that IF it is not,
679 /* getcwd() will "usually" be the correct thing... Urgh!
682 /* check pathname is absolute (begins with a / ???) */
683 if (p[0] == '/') /* assume this means we have an
686 strncpy(pname, p, pathsize);
687 if ((access(pname, 0) == 0))
688 return 0; /* file exists, return OK */
690 else /* if not, prepend getcwd() then check if file
693 getcwd(pname, pathsize);
694 long result = strlen(pname);
695 strncat(pname, "/", (pathsize - result));
697 strncat(pname, p, (pathsize - result));
699 if ((access(pname, 0) == 0))
700 return 0; /* file exists, return OK */
701 /*else name doesn't seem to exist, return FAIL
707 #ifdef MACOSX /* assume this is OSX */
709 from http://www.hmug.org/man/3/NSModule.html
711 extern int _NSGetExecutablePath(char *buf, unsigned long
714 _NSGetExecutablePath copies the path of the executable
715 into the buffer and returns 0 if the path was successfully
716 copied in the provided buffer. If the buffer is not large
717 enough, -1 is returned and the expected buffer size is
718 copied in *bufsize. Note that _NSGetExecutablePath will
719 return "a path" to the executable not a "real path" to the
720 executable. That is the path may be a symbolic link and
721 not the real file. And with deep directories the total
722 bufsize needed could be more than MAXPATHLEN.
725 char *given_path = (char*)malloc(MAXPATHLEN * 2);
726 if (!given_path) return status;
728 uint32_t npathsize = MAXPATHLEN * 2;
729 long result = _NSGetExecutablePath(given_path, &npathsize);
731 { /* OK, we got something - now try and resolve the real path...
733 if (realpath(given_path, pname) != NULL)
735 if ((access(pname, 0) == 0))
736 status = 0; /* file exists, return OK */
743 return -1; /* Path Lookup Failed */
745 //=========================================================================
749 //=========================================================================
750 std::string Utilities::GetExecutablePath()
753 int err = get_app_path(name, PATH_MAX);
756 bbtkGlobalError("Could not determine current executable path ?");
759 // remove the exe name
761 slash = strrchr(name, VALID_FILE_SEPARATOR_CHAR);
768 //=========================================================================