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 #include <ShlObj.h> // for CSIDL
61 static SGPath pathForCSIDL(int csidl, const SGPath& def)
63 typedef BOOL (WINAPI*GetSpecialFolderPath)(HWND, LPSTR, int, BOOL);
64 static GetSpecialFolderPath SHGetSpecialFolderPath = NULL;
66 // lazy open+resolve of shell32
67 if (!SHGetSpecialFolderPath) {
68 HINSTANCE shellDll = ::LoadLibrary("shell32");
69 SHGetSpecialFolderPath = (GetSpecialFolderPath) GetProcAddress(shellDll, "SHGetSpecialFolderPathA");
72 if (!SHGetSpecialFolderPath){
77 if (SHGetSpecialFolderPath(0, path, csidl, false)) {
78 return SGPath(path, def.getPermissionChecker());
85 // defined in CocoaHelpers.mm
86 SGPath appleSpecialFolder(int dirType, int domainMask, const SGPath& def);
89 static SGPath getXDGDir( const std::string& name,
91 const std::string& fallback )
93 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
95 // $XDG_CONFIG_HOME defines the base directory relative to which user specific
96 // configuration files should be stored. If $XDG_CONFIG_HOME is either not set
97 // or empty, a default equal to $HOME/.config should be used.
98 const SGPath user_dirs = SGPath::fromEnv( "XDG_CONFIG_HOME",
99 SGPath::home() / ".config")
102 // Format is XDG_xxx_DIR="$HOME/yyy", where yyy is a shell-escaped
103 // homedir-relative path, or XDG_xxx_DIR="/yyy", where /yyy is an absolute
104 // path. No other format is supported.
105 const std::string XDG_ID = "XDG_" + name + "_DIR=\"";
107 std::ifstream user_dirs_file( user_dirs.c_str() );
109 while( std::getline(user_dirs_file, line).good() )
111 if( !starts_with(line, XDG_ID) || *line.rbegin() != '"' )
114 // Extract dir from XDG_<name>_DIR="<dir>"
115 line = line.substr(XDG_ID.length(), line.length() - XDG_ID.length() - 1 );
117 const std::string HOME = "$HOME";
118 if( starts_with(line, HOME) )
119 return SGPath::home(def)
120 / simgear::strutils::unescape(line.substr(HOME.length()));
122 return SGPath(line, def.getPermissionChecker());
126 return SGPath::home(def) / fallback;
132 // For windows, replace "\" by "/".
136 string::size_type sz = path.size();
137 for ( string::size_type i = 0; i < sz; ++i ) {
138 if ( path[i] == sgDirPathSepBad ) {
139 path[i] = sgDirPathSep;
143 while ((sz>1)&&(path[sz-1]==sgDirPathSep))
150 // default constructor
151 SGPath::SGPath(PermissionChecker validator)
153 _permission_checker(validator),
161 // create a path based on "path"
162 SGPath::SGPath( const std::string& p, PermissionChecker validator )
164 _permission_checker(validator),
172 // create a path based on "path" and a "subpath"
173 SGPath::SGPath( const SGPath& p,
174 const std::string& r,
175 PermissionChecker validator )
177 _permission_checker(validator),
180 _cacheEnabled(p._cacheEnabled)
186 SGPath::SGPath(const SGPath& p) :
188 _permission_checker(p._permission_checker),
190 _rwCached(p._rwCached),
191 _cacheEnabled(p._cacheEnabled),
192 _canRead(p._canRead),
193 _canWrite(p._canWrite),
201 SGPath& SGPath::operator=(const SGPath& p)
204 _permission_checker = p._permission_checker,
206 _rwCached = p._rwCached;
207 _cacheEnabled = p._cacheEnabled;
208 _canRead = p._canRead;
209 _canWrite = p._canWrite;
213 _modTime = p._modTime;
223 void SGPath::set( const string& p ) {
230 //------------------------------------------------------------------------------
231 void SGPath::setPermissionChecker(PermissionChecker validator)
233 _permission_checker = validator;
237 //------------------------------------------------------------------------------
238 SGPath::PermissionChecker SGPath::getPermissionChecker() const
240 return _permission_checker;
243 //------------------------------------------------------------------------------
244 void SGPath::set_cached(bool cached)
246 _cacheEnabled = cached;
249 // append another piece to the existing path
250 void SGPath::append( const string& p ) {
251 if ( path.empty() ) {
254 if ( p[0] != sgDirPathSep ) {
255 path += sgDirPathSep;
264 //------------------------------------------------------------------------------
265 SGPath SGPath::operator/( const std::string& p ) const
272 //add a new path component to the existing path string
273 void SGPath::add( const string& p ) {
274 append( sgSearchPathSep+p );
278 // concatenate a string to the end of the path without inserting a
280 void SGPath::concat( const string& p ) {
281 if ( path.empty() ) {
292 // Get the file part of the path (everything after the last path sep)
293 string SGPath::file() const
295 string::size_type index = path.rfind(sgDirPathSep);
296 if (index != string::npos) {
297 return path.substr(index + 1);
304 // get the directory part of the path.
305 string SGPath::dir() const {
306 int index = path.rfind(sgDirPathSep);
308 return path.substr(0, index);
314 // get the base part of the path (everything but the extension.)
315 string SGPath::base() const
317 string::size_type index = path.rfind(".");
318 string::size_type lastSep = path.rfind(sgDirPathSep);
320 // tolerate dots inside directory names
321 if ((lastSep != string::npos) && (index < lastSep)) {
325 if (index != string::npos) {
326 return path.substr(0, index);
332 string SGPath::file_base() const
334 string::size_type index = path.rfind(sgDirPathSep);
335 if (index == string::npos) {
336 index = 0; // no separator in the name
338 ++index; // skip past the separator
341 string::size_type firstDot = path.find(".", index);
342 if (firstDot == string::npos) {
343 return path.substr(index); // no extensions
346 return path.substr(index, firstDot - index);
349 // get the extension (everything after the final ".")
350 // but make sure no "/" follows the "." character (otherwise it
351 // is has to be a directory name containing a ".").
352 string SGPath::extension() const {
353 int index = path.rfind(".");
354 if ((index >= 0) && (path.find("/", index) == string::npos)) {
355 return path.substr(index + 1);
361 string SGPath::lower_extension() const {
362 return boost::to_lower_copy(extension());
365 string SGPath::complete_lower_extension() const
367 string::size_type index = path.rfind(sgDirPathSep);
368 if (index == string::npos) {
369 index = 0; // no separator in the name
371 ++index; // skip past the separator
374 string::size_type firstDot = path.find(".", index);
375 if ((firstDot != string::npos) && (path.find(sgDirPathSep, firstDot) == string::npos)) {
376 return boost::to_lower_copy(path.substr(firstDot + 1));
382 //------------------------------------------------------------------------------
383 void SGPath::validate() const
385 if (_cached && _cacheEnabled) {
396 bool remove_trailing = false;
397 string statPath(path);
398 if ((path.length() > 1) && (path.back() == '/')) {
402 if (_stat(statPath.c_str(), &buf ) < 0) {
406 _isFile = ((S_IFREG & buf.st_mode ) !=0);
407 _isDir = ((S_IFDIR & buf.st_mode ) !=0);
408 _modTime = buf.st_mtime;
414 if (stat(path.c_str(), &buf ) < 0) {
418 _isFile = ((S_ISREG(buf.st_mode )) != 0);
419 _isDir = ((S_ISDIR(buf.st_mode )) != 0);
420 _modTime = buf.st_mtime;
427 //------------------------------------------------------------------------------
428 void SGPath::checkAccess() const
430 if( _rwCached && _cacheEnabled )
433 if( _permission_checker )
435 Permissions p = _permission_checker(*this);
448 bool SGPath::exists() const
454 //------------------------------------------------------------------------------
455 bool SGPath::canRead() const
461 //------------------------------------------------------------------------------
462 bool SGPath::canWrite() const
468 bool SGPath::isDir() const
471 return _exists && _isDir;
474 bool SGPath::isFile() const
477 return _exists && _isFile;
481 # define sgMkDir(d,m) _mkdir(d)
483 # define sgMkDir(d,m) mkdir(d,m)
487 int SGPath::create_dir( mode_t mode ) {
488 string_list dirlist = sgPathSplit(dir());
489 if ( dirlist.empty() )
491 string path = dirlist[0];
492 string_list path_elements = sgPathBranchSplit(path);
493 bool absolute = !path.empty() && path[0] == sgDirPathSep;
496 SGPath dir(absolute ? string( 1, sgDirPathSep ) : "", _permission_checker);
497 dir.concat( path_elements[0] );
499 if ( dir.str().find(':') != string::npos && path_elements.size() >= 2 ) {
500 dir.append( path_elements[1] );
506 for(; ( r = stat( dir.c_str(), &info ) ) == 0 && i < path_elements.size(); i++) {
507 dir.append(path_elements[i]);
510 return 0; // Directory already exists
514 if( !dir.canWrite() )
517 SG_WARN, "Error creating directory: (" << dir.str() << ")" <<
518 " reason: access denied" );
521 else if( sgMkDir(dir.c_str(), mode) )
524 SG_ALERT, "Error creating directory: (" << dir.str() << ")" );
528 if( i >= path_elements.size() )
531 dir.append(path_elements[i++]);
537 string_list sgPathBranchSplit( const string &dirpath ) {
538 string_list path_elements;
539 string element, path = dirpath;
540 while ( ! path.empty() ) {
541 size_t p = path.find( sgDirPathSep );
542 if ( p != string::npos ) {
543 element = path.substr( 0, p );
544 path.erase( 0, p + 1 );
549 if ( ! element.empty() )
550 path_elements.push_back( element );
552 return path_elements;
556 string_list sgPathSplit( const string &search_path ) {
557 string tmp = search_path;
564 int index = tmp.find(sgSearchPathSep);
566 result.push_back( tmp.substr(0, index) );
567 tmp = tmp.substr( index + 1 );
570 result.push_back( tmp );
578 bool SGPath::isAbsolute() const
585 // detect '[A-Za-z]:/'
586 if (path.size() > 2) {
587 if (isalpha(path[0]) && (path[1] == ':') && (path[2] == sgDirPathSep)) {
593 return (path[0] == sgDirPathSep);
596 bool SGPath::isNull() const
601 std::string SGPath::str_native() const
604 std::string s = str();
605 std::string::size_type pos;
606 std::string nativeSeparator;
607 nativeSeparator = sgDirPathSepBad;
609 while( (pos=s.find( sgDirPathSep )) != std::string::npos ) {
610 s.replace( pos, 1, nativeSeparator );
618 //------------------------------------------------------------------------------
619 bool SGPath::remove()
623 SG_LOG( SG_IO, SG_WARN, "file remove failed: (" << str() << ")"
624 " reason: access denied" );
628 int err = ::unlink(c_str());
631 SG_LOG( SG_IO, SG_WARN, "file remove failed: (" << str() << ") "
632 " reason: " << strerror(errno) );
633 // TODO check if failed unlink can really change any of the cached values
636 _cached = false; // stat again if required
641 time_t SGPath::modTime() const
647 bool SGPath::operator==(const SGPath& other) const
649 return (path == other.path);
652 bool SGPath::operator!=(const SGPath& other) const
654 return (path != other.path);
657 //------------------------------------------------------------------------------
658 bool SGPath::rename(const SGPath& newName)
660 if( !canRead() || !canWrite() || !newName.canWrite() )
662 SG_LOG( SG_IO, SG_WARN, "rename failed: from " << str() <<
663 " to " << newName.str() <<
664 " reason: access denied" );
669 if (newName.exists()) {
676 if( ::rename(c_str(), newName.c_str()) != 0 )
678 SG_LOG( SG_IO, SG_WARN, "rename failed: from " << str() <<
679 " to " << newName.str() <<
680 " reason: " << strerror(errno) );
686 // Do not remove permission checker (could happen for example if just using
687 // a std::string as new name)
688 if( newName._permission_checker )
689 _permission_checker = newName._permission_checker;
697 //------------------------------------------------------------------------------
698 SGPath SGPath::standardLocation(StandardLocation type, const SGPath& def)
706 return pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def);
708 // TODO use KnownFolders
709 // http://msdn.microsoft.com/en-us/library/bb776911%28v=vs.85%29.aspx
713 return pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def);
715 return pathForCSIDL(CSIDL_MYDOCUMENTS, def);
717 return pathForCSIDL(CSIDL_MYPICTURES, def);
719 // since this is C++, we can't include NSPathUtilities.h to access the enum
720 // values, so hard-coding them here (they are stable, don't worry)
722 return appleSpecialFolder(15, 1, def);
724 return appleSpecialFolder(12, 1, def);
726 return appleSpecialFolder(9, 1, def);
728 return appleSpecialFolder(19, 1, def);
731 return getXDGDir("DESKTOP", def, "Desktop");
733 return getXDGDir("DOWNLOADS", def, "Downloads");
735 return getXDGDir("DOCUMENTS", def, "Documents");
737 return getXDGDir("PICTURES", def, "Pictures");
742 "SGPath::standardLocation() unhandled type: " << type );
747 //------------------------------------------------------------------------------
748 SGPath SGPath::fromEnv(const char* name, const SGPath& def)
750 const char* val = getenv(name);
752 return SGPath(val, def._permission_checker);
757 //------------------------------------------------------------------------------
758 SGPath SGPath::home(const SGPath& def)
764 //------------------------------------------------------------------------------
765 SGPath SGPath::home(const SGPath& def)
767 return fromEnv("HOME", def);
771 //------------------------------------------------------------------------------
772 SGPath SGPath::desktop(const SGPath& def)
774 return standardLocation(DESKTOP, def);
777 //------------------------------------------------------------------------------
778 SGPath SGPath::documents(const SGPath& def)
780 return standardLocation(DOCUMENTS, def);
783 //------------------------------------------------------------------------------
784 std::string SGPath::realpath() const
786 #if (defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED <= 1050)
787 // Workaround for Mac OS 10.5. Somehow fgfs crashes on Mac at ::realpath.
788 // This means relative paths cannot be used on Mac OS <= 10.5
791 #if defined(_MSC_VER) /*for MS compilers */ || defined(_WIN32) /*needed for non MS windows compilers like MingW*/
792 // with absPath NULL, will allocate, and ignore length
793 char *buf = _fullpath( NULL, path.c_str(), _MAX_PATH );
796 char* buf = ::realpath(path.c_str(), NULL);
800 SG_LOG(SG_IO, SG_ALERT, "ERROR: The path '" << path << "' does not exist in the file system.");