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
60 #include <versionhelpers.h>
62 static SGPath pathForCSIDL(int csidl, const SGPath& def)
64 typedef BOOL (WINAPI*GetSpecialFolderPath)(HWND, LPSTR, int, BOOL);
65 static GetSpecialFolderPath SHGetSpecialFolderPath = NULL;
67 // lazy open+resolve of shell32
68 if (!SHGetSpecialFolderPath) {
69 HINSTANCE shellDll = ::LoadLibrary("shell32");
70 SHGetSpecialFolderPath = (GetSpecialFolderPath) GetProcAddress(shellDll, "SHGetSpecialFolderPathA");
73 if (!SHGetSpecialFolderPath){
78 if (SHGetSpecialFolderPath(0, path, csidl, false)) {
79 return SGPath(path, def.getPermissionChecker());
85 static SGPath pathForKnownFolder(REFKNOWNFOLDERID folderId, const SGPath& def)
87 typedef HRESULT (WINAPI*PSHGKFP)(REFKNOWNFOLDERID, DWORD, HANDLE, PWSTR*);
89 HINSTANCE shellDll = LoadLibrary(TEXT("shell32"));
90 if (shellDll != NULL) {
91 PSHGKFP pSHGetKnownFolderPath = (PSHGKFP) GetProcAddress(shellDll, "SHGetKnownFolderPath");
92 if (pSHGetKnownFolderPath != NULL) {
93 // system call will allocate dynamic memory... which we must release when done
94 wchar_t* localFolder = 0;
96 if (pSHGetKnownFolderPath(folderId, KF_FLAG_DEFAULT_PATH, NULL, &localFolder) == S_OK) {
97 // copy into local memory
100 if (wcstombs_s(&len, path, localFolder, MAX_PATH) != S_OK) {
102 SG_LOG(SG_GENERAL, SG_WARN, "WCS to MBS failed");
105 SGPath folder_path = SGPath(path, def.getPermissionChecker());
107 // release dynamic memory
108 CoTaskMemFree(static_cast<void*>(localFolder));
114 FreeLibrary(shellDll);
122 // defined in CocoaHelpers.mm
123 SGPath appleSpecialFolder(int dirType, int domainMask, const SGPath& def);
126 static SGPath getXDGDir( const std::string& name,
128 const std::string& fallback )
130 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
132 // $XDG_CONFIG_HOME defines the base directory relative to which user specific
133 // configuration files should be stored. If $XDG_CONFIG_HOME is either not set
134 // or empty, a default equal to $HOME/.config should be used.
135 const SGPath user_dirs = SGPath::fromEnv( "XDG_CONFIG_HOME",
136 SGPath::home() / ".config")
139 // Format is XDG_xxx_DIR="$HOME/yyy", where yyy is a shell-escaped
140 // homedir-relative path, or XDG_xxx_DIR="/yyy", where /yyy is an absolute
141 // path. No other format is supported.
142 const std::string XDG_ID = "XDG_" + name + "_DIR=\"";
144 std::ifstream user_dirs_file( user_dirs.c_str() );
146 while( std::getline(user_dirs_file, line).good() )
148 if( !starts_with(line, XDG_ID) || *line.rbegin() != '"' )
151 // Extract dir from XDG_<name>_DIR="<dir>"
152 line = line.substr(XDG_ID.length(), line.length() - XDG_ID.length() - 1 );
154 const std::string HOME = "$HOME";
155 if( starts_with(line, HOME) )
156 return SGPath::home(def)
157 / simgear::strutils::unescape(line.substr(HOME.length()));
159 return SGPath(line, def.getPermissionChecker());
163 return SGPath::home(def) / fallback;
169 // For windows, replace "\" by "/".
173 string::size_type sz = path.size();
174 for ( string::size_type i = 0; i < sz; ++i ) {
175 if ( path[i] == sgDirPathSepBad ) {
176 path[i] = sgDirPathSep;
180 while ((sz>1)&&(path[sz-1]==sgDirPathSep))
187 // default constructor
188 SGPath::SGPath(PermissionChecker validator)
190 _permission_checker(validator),
198 // create a path based on "path"
199 SGPath::SGPath( const std::string& p, PermissionChecker validator )
201 _permission_checker(validator),
209 // create a path based on "path" and a "subpath"
210 SGPath::SGPath( const SGPath& p,
211 const std::string& r,
212 PermissionChecker validator )
214 _permission_checker(validator),
217 _cacheEnabled(p._cacheEnabled)
223 SGPath::SGPath(const SGPath& p) :
225 _permission_checker(p._permission_checker),
227 _rwCached(p._rwCached),
228 _cacheEnabled(p._cacheEnabled),
229 _canRead(p._canRead),
230 _canWrite(p._canWrite),
238 SGPath& SGPath::operator=(const SGPath& p)
241 _permission_checker = p._permission_checker,
243 _rwCached = p._rwCached;
244 _cacheEnabled = p._cacheEnabled;
245 _canRead = p._canRead;
246 _canWrite = p._canWrite;
250 _modTime = p._modTime;
260 void SGPath::set( const string& p ) {
267 //------------------------------------------------------------------------------
268 void SGPath::setPermissionChecker(PermissionChecker validator)
270 _permission_checker = validator;
274 //------------------------------------------------------------------------------
275 SGPath::PermissionChecker SGPath::getPermissionChecker() const
277 return _permission_checker;
280 //------------------------------------------------------------------------------
281 void SGPath::set_cached(bool cached)
283 _cacheEnabled = cached;
286 // append another piece to the existing path
287 void SGPath::append( const string& p ) {
288 if ( path.empty() ) {
291 if ( p[0] != sgDirPathSep ) {
292 path += sgDirPathSep;
301 //------------------------------------------------------------------------------
302 SGPath SGPath::operator/( const std::string& p ) const
309 //add a new path component to the existing path string
310 void SGPath::add( const string& p ) {
311 append( sgSearchPathSep+p );
315 // concatenate a string to the end of the path without inserting a
317 void SGPath::concat( const string& p ) {
318 if ( path.empty() ) {
329 // Get the file part of the path (everything after the last path sep)
330 string SGPath::file() const
332 string::size_type index = path.rfind(sgDirPathSep);
333 if (index != string::npos) {
334 return path.substr(index + 1);
341 // get the directory part of the path.
342 string SGPath::dir() const {
343 int index = path.rfind(sgDirPathSep);
345 return path.substr(0, index);
351 // get the base part of the path (everything but the extension.)
352 string SGPath::base() const
354 string::size_type index = path.rfind(".");
355 string::size_type lastSep = path.rfind(sgDirPathSep);
357 // tolerate dots inside directory names
358 if ((lastSep != string::npos) && (index < lastSep)) {
362 if (index != string::npos) {
363 return path.substr(0, index);
369 string SGPath::file_base() const
371 string::size_type index = path.rfind(sgDirPathSep);
372 if (index == string::npos) {
373 index = 0; // no separator in the name
375 ++index; // skip past the separator
378 string::size_type firstDot = path.find(".", index);
379 if (firstDot == string::npos) {
380 return path.substr(index); // no extensions
383 return path.substr(index, firstDot - index);
386 // get the extension (everything after the final ".")
387 // but make sure no "/" follows the "." character (otherwise it
388 // is has to be a directory name containing a ".").
389 string SGPath::extension() const {
390 int index = path.rfind(".");
391 if ((index >= 0) && (path.find("/", index) == string::npos)) {
392 return path.substr(index + 1);
398 string SGPath::lower_extension() const {
399 return boost::to_lower_copy(extension());
402 string SGPath::complete_lower_extension() const
404 string::size_type index = path.rfind(sgDirPathSep);
405 if (index == string::npos) {
406 index = 0; // no separator in the name
408 ++index; // skip past the separator
411 string::size_type firstDot = path.find(".", index);
412 if ((firstDot != string::npos) && (path.find(sgDirPathSep, firstDot) == string::npos)) {
413 return boost::to_lower_copy(path.substr(firstDot + 1));
419 //------------------------------------------------------------------------------
420 void SGPath::validate() const
422 if (_cached && _cacheEnabled) {
433 bool remove_trailing = false;
434 string statPath(path);
435 if ((path.length() > 1) && (path.back() == '/')) {
439 if (_stat(statPath.c_str(), &buf ) < 0) {
443 _isFile = ((S_IFREG & buf.st_mode ) !=0);
444 _isDir = ((S_IFDIR & buf.st_mode ) !=0);
445 _modTime = buf.st_mtime;
451 if (stat(path.c_str(), &buf ) < 0) {
455 _isFile = ((S_ISREG(buf.st_mode )) != 0);
456 _isDir = ((S_ISDIR(buf.st_mode )) != 0);
457 _modTime = buf.st_mtime;
464 //------------------------------------------------------------------------------
465 void SGPath::checkAccess() const
467 if( _rwCached && _cacheEnabled )
470 if( _permission_checker )
472 Permissions p = _permission_checker(*this);
485 bool SGPath::exists() const
491 //------------------------------------------------------------------------------
492 bool SGPath::canRead() const
498 //------------------------------------------------------------------------------
499 bool SGPath::canWrite() const
505 bool SGPath::isDir() const
508 return _exists && _isDir;
511 bool SGPath::isFile() const
514 return _exists && _isFile;
517 //------------------------------------------------------------------------------
519 # define sgMkDir(d,m) _mkdir(d)
521 # define sgMkDir(d,m) mkdir(d,m)
524 int SGPath::create_dir(mode_t mode)
529 SG_WARN, "Error creating directory for '" << str() << "'"
530 " reason: access denied" );
534 string_list dirlist = sgPathSplit(dir());
535 if ( dirlist.empty() )
537 string path = dirlist[0];
538 string_list path_elements = sgPathBranchSplit(path);
539 bool absolute = !path.empty() && path[0] == sgDirPathSep;
542 SGPath dir(absolute ? string( 1, sgDirPathSep ) : "", _permission_checker);
543 dir.concat( path_elements[0] );
545 if ( dir.str().find(':') != string::npos && path_elements.size() >= 2 ) {
546 dir.append( path_elements[1] );
552 for(; (r = stat(dir.c_str(), &info)) == 0 && i < path_elements.size(); ++i)
553 dir.append(path_elements[i]);
555 return 0; // Directory already exists
559 if( sgMkDir(dir.c_str(), mode) )
562 SG_ALERT, "Error creating directory: (" << dir.str() << ")" );
566 SG_LOG(SG_IO, SG_DEBUG, "Directory created: " << dir.str());
568 if( i >= path_elements.size() )
571 dir.append(path_elements[i++]);
577 string_list sgPathBranchSplit( const string &dirpath ) {
578 string_list path_elements;
579 string element, path = dirpath;
580 while ( ! path.empty() ) {
581 size_t p = path.find( sgDirPathSep );
582 if ( p != string::npos ) {
583 element = path.substr( 0, p );
584 path.erase( 0, p + 1 );
589 if ( ! element.empty() )
590 path_elements.push_back( element );
592 return path_elements;
596 string_list sgPathSplit( const string &search_path ) {
597 string tmp = search_path;
604 int index = tmp.find(sgSearchPathSep);
606 result.push_back( tmp.substr(0, index) );
607 tmp = tmp.substr( index + 1 );
610 result.push_back( tmp );
618 bool SGPath::isAbsolute() const
625 // detect '[A-Za-z]:/'
626 if (path.size() > 2) {
627 if (isalpha(path[0]) && (path[1] == ':') && (path[2] == sgDirPathSep)) {
633 return (path[0] == sgDirPathSep);
636 bool SGPath::isNull() const
641 std::string SGPath::str_native() const
644 std::string s = str();
645 std::string::size_type pos;
646 std::string nativeSeparator;
647 nativeSeparator = sgDirPathSepBad;
649 while( (pos=s.find( sgDirPathSep )) != std::string::npos ) {
650 s.replace( pos, 1, nativeSeparator );
658 //------------------------------------------------------------------------------
659 bool SGPath::remove()
663 SG_LOG( SG_IO, SG_WARN, "file remove failed: (" << str() << ")"
664 " reason: access denied" );
668 int err = ::unlink(c_str());
671 SG_LOG( SG_IO, SG_WARN, "file remove failed: (" << str() << ") "
672 " reason: " << strerror(errno) );
673 // TODO check if failed unlink can really change any of the cached values
676 _cached = false; // stat again if required
681 time_t SGPath::modTime() const
687 bool SGPath::operator==(const SGPath& other) const
689 return (path == other.path);
692 bool SGPath::operator!=(const SGPath& other) const
694 return (path != other.path);
697 //------------------------------------------------------------------------------
698 bool SGPath::rename(const SGPath& newName)
700 if( !canRead() || !canWrite() || !newName.canWrite() )
702 SG_LOG( SG_IO, SG_WARN, "rename failed: from " << str() <<
703 " to " << newName.str() <<
704 " reason: access denied" );
709 if (newName.exists()) {
716 if( ::rename(c_str(), newName.c_str()) != 0 )
718 SG_LOG( SG_IO, SG_WARN, "rename failed: from " << str() <<
719 " to " << newName.str() <<
720 " reason: " << strerror(errno) );
726 // Do not remove permission checker (could happen for example if just using
727 // a std::string as new name)
728 if( newName._permission_checker )
729 _permission_checker = newName._permission_checker;
737 //------------------------------------------------------------------------------
738 SGPath SGPath::standardLocation(StandardLocation type, const SGPath& def)
747 if (IsWindowsVistaOrGreater())
748 return pathForKnownFolder(FOLDERID_Desktop, def);
750 return pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def);
753 if (IsWindowsVistaOrGreater())
754 return pathForKnownFolder(FOLDERID_Downloads, def);
759 return pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def);
762 if (IsWindowsVistaOrGreater())
763 return pathForKnownFolder(FOLDERID_Documents, def);
765 return pathForCSIDL(CSIDL_MYDOCUMENTS, def);
768 if (IsWindowsVistaOrGreater())
769 return pathForKnownFolder(FOLDERID_Pictures, def);
771 return pathForCSIDL(CSIDL_MYPICTURES, def);
774 // since this is C++, we can't include NSPathUtilities.h to access the enum
775 // values, so hard-coding them here (they are stable, don't worry)
777 return appleSpecialFolder(15, 1, def);
779 return appleSpecialFolder(12, 1, def);
781 return appleSpecialFolder(9, 1, def);
783 return appleSpecialFolder(19, 1, def);
786 return getXDGDir("DESKTOP", def, "Desktop");
788 return getXDGDir("DOWNLOADS", def, "Downloads");
790 return getXDGDir("DOCUMENTS", def, "Documents");
792 return getXDGDir("PICTURES", def, "Pictures");
797 "SGPath::standardLocation() unhandled type: " << type );
802 //------------------------------------------------------------------------------
803 SGPath SGPath::fromEnv(const char* name, const SGPath& def)
805 const char* val = getenv(name);
807 return SGPath(val, def._permission_checker);
811 //------------------------------------------------------------------------------
812 SGPath SGPath::home(const SGPath& def)
815 return fromEnv("USERPROFILE", def);
817 return fromEnv("HOME", def);
821 //------------------------------------------------------------------------------
822 SGPath SGPath::desktop(const SGPath& def)
824 return standardLocation(DESKTOP, def);
827 //------------------------------------------------------------------------------
828 SGPath SGPath::documents(const SGPath& def)
830 return standardLocation(DOCUMENTS, def);
833 //------------------------------------------------------------------------------
834 std::string SGPath::realpath() const
836 #if (defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED <= 1050)
837 // Workaround for Mac OS 10.5. Somehow fgfs crashes on Mac at ::realpath.
838 // This means relative paths cannot be used on Mac OS <= 10.5
841 #if defined(_MSC_VER) /*for MS compilers */ || defined(_WIN32) /*needed for non MS windows compilers like MingW*/
842 // with absPath NULL, will allocate, and ignore length
843 char *buf = _fullpath( NULL, path.c_str(), _MAX_PATH );
846 char* buf = ::realpath(path.c_str(), NULL);
850 SG_LOG(SG_IO, SG_ALERT, "ERROR: The path '" << path << "' does not exist in the file system.");