1 // sg_path.cxx -- routines to abstract out path separator differences
2 // between MacOS and the rest of the world
4 // Written by Curtis L. Olson, started April 1999.
6 // Copyright (C) 1999 Curtis L. Olson - http://www.flightgear.org/~curt
8 // This library is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU Library General Public
10 // License as published by the Free Software Foundation; either
11 // version 2 of the License, or (at your option) any later version.
13 // This library is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // Library General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 #include <simgear/compiler.h>
27 #include <simgear_config.h>
28 #include <simgear/debug/logstream.hxx>
29 #include <simgear/misc/strutils.hxx>
38 #include "sg_path.hxx"
40 #include <boost/algorithm/string/case_conv.hpp>
43 using simgear::strutils::starts_with;
46 * define directory path separators
49 static const char sgDirPathSep = '/';
50 static const char sgDirPathSepBad = '\\';
53 static const char sgSearchPathSep = ';';
55 static const char sgSearchPathSep = ':';
59 // For windows, replace "\" by "/".
63 string::size_type sz = path.size();
64 for ( string::size_type i = 0; i < sz; ++i ) {
65 if ( path[i] == sgDirPathSepBad ) {
66 path[i] = sgDirPathSep;
70 while ((sz>1)&&(path[sz-1]==sgDirPathSep))
77 // default constructor
78 SGPath::SGPath(PermissonChecker validator)
80 _permisson_checker(validator),
88 // create a path based on "path"
89 SGPath::SGPath( const std::string& p, PermissonChecker validator )
91 _permisson_checker(validator),
99 // create a path based on "path" and a "subpath"
100 SGPath::SGPath( const SGPath& p,
101 const std::string& r,
102 PermissonChecker validator )
104 _permisson_checker(validator),
107 _cacheEnabled(p._cacheEnabled)
113 SGPath::SGPath(const SGPath& p) :
115 _permisson_checker(p._permisson_checker),
117 _rwCached(p._rwCached),
118 _cacheEnabled(p._cacheEnabled),
119 _canRead(p._canRead),
120 _canWrite(p._canWrite),
128 SGPath& SGPath::operator=(const SGPath& p)
131 _permisson_checker = p._permisson_checker,
133 _rwCached = p._rwCached;
134 _cacheEnabled = p._cacheEnabled;
135 _canRead = p._canRead;
136 _canWrite = p._canWrite;
140 _modTime = p._modTime;
150 void SGPath::set( const string& p ) {
157 //------------------------------------------------------------------------------
158 void SGPath::setPermissonChecker(PermissonChecker validator)
160 _permisson_checker = validator;
164 //------------------------------------------------------------------------------
165 SGPath::PermissonChecker SGPath::getPermissonChecker() const
167 return _permisson_checker;
170 //------------------------------------------------------------------------------
171 void SGPath::set_cached(bool cached)
173 _cacheEnabled = cached;
176 // append another piece to the existing path
177 void SGPath::append( const string& p ) {
178 if ( path.empty() ) {
181 if ( p[0] != sgDirPathSep ) {
182 path += sgDirPathSep;
191 //------------------------------------------------------------------------------
192 SGPath SGPath::operator/( const std::string& p ) const
199 //add a new path component to the existing path string
200 void SGPath::add( const string& p ) {
201 append( sgSearchPathSep+p );
205 // concatenate a string to the end of the path without inserting a
207 void SGPath::concat( const string& p ) {
208 if ( path.empty() ) {
219 // Get the file part of the path (everything after the last path sep)
220 string SGPath::file() const
222 string::size_type index = path.rfind(sgDirPathSep);
223 if (index != string::npos) {
224 return path.substr(index + 1);
231 // get the directory part of the path.
232 string SGPath::dir() const {
233 int index = path.rfind(sgDirPathSep);
235 return path.substr(0, index);
241 // get the base part of the path (everything but the extension.)
242 string SGPath::base() const
244 string::size_type index = path.rfind(".");
245 string::size_type lastSep = path.rfind(sgDirPathSep);
247 // tolerate dots inside directory names
248 if ((lastSep != string::npos) && (index < lastSep)) {
252 if (index != string::npos) {
253 return path.substr(0, index);
259 string SGPath::file_base() const
261 string::size_type index = path.rfind(sgDirPathSep);
262 if (index == string::npos) {
263 index = 0; // no separator in the name
265 ++index; // skip past the separator
268 string::size_type firstDot = path.find(".", index);
269 if (firstDot == string::npos) {
270 return path.substr(index); // no extensions
273 return path.substr(index, firstDot - index);
276 // get the extension (everything after the final ".")
277 // but make sure no "/" follows the "." character (otherwise it
278 // is has to be a directory name containing a ".").
279 string SGPath::extension() const {
280 int index = path.rfind(".");
281 if ((index >= 0) && (path.find("/", index) == string::npos)) {
282 return path.substr(index + 1);
288 string SGPath::lower_extension() const {
289 return boost::to_lower_copy(extension());
292 string SGPath::complete_lower_extension() const
294 string::size_type index = path.rfind(sgDirPathSep);
295 if (index == string::npos) {
296 index = 0; // no separator in the name
298 ++index; // skip past the separator
301 string::size_type firstDot = path.find(".", index);
302 if ((firstDot != string::npos) && (path.find(sgDirPathSep, firstDot) == string::npos)) {
303 return boost::to_lower_copy(path.substr(firstDot + 1));
309 void SGPath::validate() const
311 if (_cached && _cacheEnabled) {
318 bool remove_trailing = false;
319 if ( path.length() > 1 && path[path.length()-1] == '/' )
320 remove_trailing=true;
321 if (_stat (path.substr(0,remove_trailing?path.length()-1:path.length()).c_str(), &buf ) < 0) {
325 _isFile = ((S_IFREG & buf.st_mode ) !=0);
326 _isDir = ((S_IFDIR & buf.st_mode ) !=0);
327 _modTime = buf.st_mtime;
333 if (stat(path.c_str(), &buf ) < 0) {
337 _isFile = ((S_ISREG(buf.st_mode )) != 0);
338 _isDir = ((S_ISDIR(buf.st_mode )) != 0);
339 _modTime = buf.st_mtime;
346 void SGPath::checkAccess() const
348 if( _rwCached && _cacheEnabled )
351 if( _permisson_checker )
353 Permissions p = _permisson_checker(*this);
366 bool SGPath::exists() const
372 //------------------------------------------------------------------------------
373 bool SGPath::canRead() const
379 //------------------------------------------------------------------------------
380 bool SGPath::canWrite() const
386 bool SGPath::isDir() const
389 return _exists && _isDir;
392 bool SGPath::isFile() const
395 return _exists && _isFile;
399 # define sgMkDir(d,m) _mkdir(d)
401 # define sgMkDir(d,m) mkdir(d,m)
405 int SGPath::create_dir( mode_t mode ) {
406 string_list dirlist = sgPathSplit(dir());
407 if ( dirlist.empty() )
409 string path = dirlist[0];
410 string_list path_elements = sgPathBranchSplit(path);
411 bool absolute = !path.empty() && path[0] == sgDirPathSep;
414 SGPath dir(absolute ? string( 1, sgDirPathSep ) : "", _permisson_checker);
415 dir.concat( path_elements[0] );
417 if ( dir.str().find(':') != string::npos && path_elements.size() >= 2 ) {
418 dir.append( path_elements[1] );
424 for(; ( r = stat( dir.c_str(), &info ) ) == 0 && i < path_elements.size(); i++) {
425 dir.append(path_elements[i]);
428 return 0; // Directory already exists
432 if( !dir.canWrite() )
435 SG_ALERT, "Error creating directory: (" << dir.str() << ")" <<
436 " reason: access denied" );
439 else if( sgMkDir(dir.c_str(), mode) )
442 SG_ALERT, "Error creating directory: (" << dir.str() << ")" );
446 if( i >= path_elements.size() )
449 dir.append(path_elements[i++]);
455 string_list sgPathBranchSplit( const string &dirpath ) {
456 string_list path_elements;
457 string element, path = dirpath;
458 while ( ! path.empty() ) {
459 size_t p = path.find( sgDirPathSep );
460 if ( p != string::npos ) {
461 element = path.substr( 0, p );
462 path.erase( 0, p + 1 );
467 if ( ! element.empty() )
468 path_elements.push_back( element );
470 return path_elements;
474 string_list sgPathSplit( const string &search_path ) {
475 string tmp = search_path;
482 int index = tmp.find(sgSearchPathSep);
484 result.push_back( tmp.substr(0, index) );
485 tmp = tmp.substr( index + 1 );
488 result.push_back( tmp );
496 bool SGPath::isAbsolute() const
503 // detect '[A-Za-z]:/'
504 if (path.size() > 2) {
505 if (isalpha(path[0]) && (path[1] == ':') && (path[2] == sgDirPathSep)) {
511 return (path[0] == sgDirPathSep);
514 bool SGPath::isNull() const
519 std::string SGPath::str_native() const
522 std::string s = str();
523 std::string::size_type pos;
524 std::string nativeSeparator;
525 nativeSeparator = sgDirPathSepBad;
527 while( (pos=s.find( sgDirPathSep )) != std::string::npos ) {
528 s.replace( pos, 1, nativeSeparator );
536 //------------------------------------------------------------------------------
537 bool SGPath::remove()
541 SG_LOG( SG_IO, SG_WARN, "file remove failed: (" << str() << ")"
542 " reason: access denied" );
546 int err = ::unlink(c_str());
549 SG_LOG( SG_IO, SG_WARN, "file remove failed: (" << str() << ") "
550 " reason: " << strerror(errno) );
551 // TODO check if failed unlink can really change any of the cached values
554 _cached = false; // stat again if required
559 time_t SGPath::modTime() const
565 bool SGPath::operator==(const SGPath& other) const
567 return (path == other.path);
570 bool SGPath::operator!=(const SGPath& other) const
572 return (path != other.path);
575 //------------------------------------------------------------------------------
576 bool SGPath::rename(const SGPath& newName)
578 if( !newName.canWrite() )
580 SG_LOG( SG_IO, SG_WARN, "rename failed: from " << str() <<
581 " to " << newName.str() <<
582 " reason: access denied" );
587 if (newName.exists()) {
594 if( ::rename(c_str(), newName.c_str()) != 0 )
596 SG_LOG( SG_IO, SG_WARN, "rename failed: from " << str() <<
597 " to " << newName.str() <<
598 " reason: " << strerror(errno) );
609 //------------------------------------------------------------------------------
610 SGPath SGPath::fromEnv(const char* name, const SGPath& def)
612 const char* val = getenv(name);
614 return SGPath(val, def._permisson_checker);
619 //------------------------------------------------------------------------------
620 SGPath SGPath::home()
626 //------------------------------------------------------------------------------
627 SGPath SGPath::home()
629 return fromEnv("HOME");
635 #include <ShlObj.h> // for CSIDL
637 //------------------------------------------------------------------------------
638 SGPath SGPath::desktop()
640 typedef BOOL (WINAPI*GetSpecialFolderPath)(HWND, LPSTR, int, BOOL);
641 static GetSpecialFolderPath SHGetSpecialFolderPath = NULL;
643 // lazy open+resolve of shell32
644 if (!SHGetSpecialFolderPath) {
645 HINSTANCE shellDll = ::LoadLibrary("shell32");
646 SHGetSpecialFolderPath = (GetSpecialFolderPath) GetProcAddress(shellDll, "SHGetSpecialFolderPathA");
649 if (!SHGetSpecialFolderPath){
654 if (SHGetSpecialFolderPath(0, path, CSIDL_DESKTOPDIRECTORY, false)) {
658 SG_LOG(SG_GENERAL, SG_ALERT, "SGPath::desktop() failed, bad" );
662 #include <CoreServices/CoreServices.h>
664 //------------------------------------------------------------------------------
665 SGPath SGPath::desktop()
668 OSErr err = FSFindFolder(kUserDomain, kDesktopFolderType, false, &ref);
673 unsigned char path[1024];
674 if (FSRefMakePath(&ref, path, 1024) != noErr) {
678 return SGPath((const char*) path);
681 //------------------------------------------------------------------------------
682 SGPath SGPath::desktop()
684 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
686 // $XDG_CONFIG_HOME defines the base directory relative to which user specific
687 // configuration files should be stored. If $XDG_CONFIG_HOME is either not set
688 // or empty, a default equal to $HOME/.config should be used.
689 const SGPath user_dirs = fromEnv("XDG_CONFIG_HOME", home() / ".config")
692 // Format is XDG_xxx_DIR="$HOME/yyy", where yyy is a shell-escaped
693 // homedir-relative path, or XDG_xxx_DIR="/yyy", where /yyy is an absolute
694 // path. No other format is supported.
695 const std::string DESKTOP = "XDG_DESKTOP_DIR=\"";
697 std::ifstream user_dirs_file( user_dirs.c_str() );
699 while( std::getline(user_dirs_file, line).good() )
701 if( !starts_with(line, DESKTOP) || *line.rbegin() != '"' )
704 // Extract dir from XDG_DESKTOP_DIR="<dir>"
705 line = line.substr(DESKTOP.length(), line.length() - DESKTOP.length() - 1 );
707 const std::string HOME = "$HOME";
708 if( starts_with(line, HOME) )
709 return home() / simgear::strutils::unescape(line.substr(HOME.length()));
714 return home() / "Desktop";
718 std::string SGPath::realpath() const
720 #if (defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED <= 1050)
721 // Workaround for Mac OS 10.5. Somehow fgfs crashes on Mac at ::realpath.
722 // This means relative paths cannot be used on Mac OS <= 10.5
725 #if defined(_MSC_VER) /*for MS compilers */ || defined(_WIN32) /*needed for non MS windows compilers like MingW*/
726 // with absPath NULL, will allocate, and ignore length
727 char *buf = _fullpath( NULL, path.c_str(), _MAX_PATH );
730 char* buf = ::realpath(path.c_str(), NULL);
734 SG_LOG(SG_IO, SG_ALERT, "ERROR: The path '" << path << "' does not exist in the file system.");