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 // TODO: replace this include file with the official <versionhelpers.h> header
61 // included in the Windows 8.1 SDK
62 #include "sgversionhelpers.hxx"
64 static SGPath pathForCSIDL(int csidl, const SGPath& def)
66 typedef BOOL (WINAPI*GetSpecialFolderPath)(HWND, LPSTR, int, BOOL);
67 static GetSpecialFolderPath SHGetSpecialFolderPath = NULL;
69 // lazy open+resolve of shell32
70 if (!SHGetSpecialFolderPath) {
71 HINSTANCE shellDll = ::LoadLibrary("shell32");
72 SHGetSpecialFolderPath = (GetSpecialFolderPath) GetProcAddress(shellDll, "SHGetSpecialFolderPathA");
75 if (!SHGetSpecialFolderPath){
80 if (SHGetSpecialFolderPath(0, path, csidl, false)) {
81 return SGPath(path, def.getPermissionChecker());
87 static SGPath pathForKnownFolder(REFKNOWNFOLDERID folderId, const SGPath& def)
89 typedef HRESULT (WINAPI*PSHGKFP)(REFKNOWNFOLDERID, DWORD, HANDLE, PWSTR*);
91 HINSTANCE shellDll = LoadLibrary(TEXT("shell32"));
92 if (shellDll != NULL) {
93 PSHGKFP pSHGetKnownFolderPath = (PSHGKFP) GetProcAddress(shellDll, "SHGetKnownFolderPath");
94 if (pSHGetKnownFolderPath != NULL) {
95 // system call will allocate dynamic memory... which we must release when done
96 wchar_t* localFolder = 0;
98 if (pSHGetKnownFolderPath(folderId, KF_FLAG_DEFAULT_PATH, NULL, &localFolder) == S_OK) {
99 // copy into local memory
102 if (wcstombs_s(&len, path, localFolder, MAX_PATH) != S_OK) {
104 SG_LOG(SG_GENERAL, SG_WARN, "WCS to MBS failed");
107 SGPath folder_path = SGPath(path, def.getPermissionChecker());
109 // release dynamic memory
110 CoTaskMemFree(static_cast<void*>(localFolder));
116 FreeLibrary(shellDll);
124 // defined in CocoaHelpers.mm
125 SGPath appleSpecialFolder(int dirType, int domainMask, const SGPath& def);
128 static SGPath getXDGDir( const std::string& name,
130 const std::string& fallback )
132 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
134 // $XDG_CONFIG_HOME defines the base directory relative to which user specific
135 // configuration files should be stored. If $XDG_CONFIG_HOME is either not set
136 // or empty, a default equal to $HOME/.config should be used.
137 const SGPath user_dirs = SGPath::fromEnv( "XDG_CONFIG_HOME",
138 SGPath::home() / ".config")
141 // Format is XDG_xxx_DIR="$HOME/yyy", where yyy is a shell-escaped
142 // homedir-relative path, or XDG_xxx_DIR="/yyy", where /yyy is an absolute
143 // path. No other format is supported.
144 const std::string XDG_ID = "XDG_" + name + "_DIR=\"";
146 std::ifstream user_dirs_file( user_dirs.c_str() );
148 while( std::getline(user_dirs_file, line).good() )
150 if( !starts_with(line, XDG_ID) || *line.rbegin() != '"' )
153 // Extract dir from XDG_<name>_DIR="<dir>"
154 line = line.substr(XDG_ID.length(), line.length() - XDG_ID.length() - 1 );
156 const std::string HOME = "$HOME";
157 if( starts_with(line, HOME) )
158 return SGPath::home(def)
159 / simgear::strutils::unescape(line.substr(HOME.length()));
161 return SGPath(line, def.getPermissionChecker());
165 return SGPath::home(def) / fallback;
171 // For windows, replace "\" by "/".
175 string::size_type sz = path.size();
176 for ( string::size_type i = 0; i < sz; ++i ) {
177 if ( path[i] == sgDirPathSepBad ) {
178 path[i] = sgDirPathSep;
182 while ((sz>1)&&(path[sz-1]==sgDirPathSep))
189 // default constructor
190 SGPath::SGPath(PermissionChecker validator)
192 _permission_checker(validator),
200 // create a path based on "path"
201 SGPath::SGPath( const std::string& p, PermissionChecker validator )
203 _permission_checker(validator),
211 // create a path based on "path" and a "subpath"
212 SGPath::SGPath( const SGPath& p,
213 const std::string& r,
214 PermissionChecker validator )
216 _permission_checker(validator),
219 _cacheEnabled(p._cacheEnabled)
225 SGPath::SGPath(const SGPath& p) :
227 _permission_checker(p._permission_checker),
229 _rwCached(p._rwCached),
230 _cacheEnabled(p._cacheEnabled),
231 _canRead(p._canRead),
232 _canWrite(p._canWrite),
240 SGPath& SGPath::operator=(const SGPath& p)
243 _permission_checker = p._permission_checker,
245 _rwCached = p._rwCached;
246 _cacheEnabled = p._cacheEnabled;
247 _canRead = p._canRead;
248 _canWrite = p._canWrite;
252 _modTime = p._modTime;
262 void SGPath::set( const string& p ) {
269 //------------------------------------------------------------------------------
270 void SGPath::setPermissionChecker(PermissionChecker validator)
272 _permission_checker = validator;
276 //------------------------------------------------------------------------------
277 SGPath::PermissionChecker SGPath::getPermissionChecker() const
279 return _permission_checker;
282 //------------------------------------------------------------------------------
283 void SGPath::set_cached(bool cached)
285 _cacheEnabled = cached;
288 // append another piece to the existing path
289 void SGPath::append( const string& p ) {
290 if ( path.empty() ) {
293 if ( p[0] != sgDirPathSep ) {
294 path += sgDirPathSep;
303 //------------------------------------------------------------------------------
304 SGPath SGPath::operator/( const std::string& p ) const
311 //add a new path component to the existing path string
312 void SGPath::add( const string& p ) {
313 append( sgSearchPathSep+p );
317 // concatenate a string to the end of the path without inserting a
319 void SGPath::concat( const string& p ) {
320 if ( path.empty() ) {
331 // Get the file part of the path (everything after the last path sep)
332 string SGPath::file() const
334 string::size_type index = path.rfind(sgDirPathSep);
335 if (index != string::npos) {
336 return path.substr(index + 1);
343 // get the directory part of the path.
344 string SGPath::dir() const {
345 int index = path.rfind(sgDirPathSep);
347 return path.substr(0, index);
353 // get the base part of the path (everything but the extension.)
354 string SGPath::base() const
356 string::size_type index = path.rfind(".");
357 string::size_type lastSep = path.rfind(sgDirPathSep);
359 // tolerate dots inside directory names
360 if ((lastSep != string::npos) && (index < lastSep)) {
364 if (index != string::npos) {
365 return path.substr(0, index);
371 string SGPath::file_base() const
373 string::size_type index = path.rfind(sgDirPathSep);
374 if (index == string::npos) {
375 index = 0; // no separator in the name
377 ++index; // skip past the separator
380 string::size_type firstDot = path.find(".", index);
381 if (firstDot == string::npos) {
382 return path.substr(index); // no extensions
385 return path.substr(index, firstDot - index);
388 // get the extension (everything after the final ".")
389 // but make sure no "/" follows the "." character (otherwise it
390 // is has to be a directory name containing a ".").
391 string SGPath::extension() const {
392 int index = path.rfind(".");
393 if ((index >= 0) && (path.find("/", index) == string::npos)) {
394 return path.substr(index + 1);
400 string SGPath::lower_extension() const {
401 return boost::to_lower_copy(extension());
404 string SGPath::complete_lower_extension() const
406 string::size_type index = path.rfind(sgDirPathSep);
407 if (index == string::npos) {
408 index = 0; // no separator in the name
410 ++index; // skip past the separator
413 string::size_type firstDot = path.find(".", index);
414 if ((firstDot != string::npos) && (path.find(sgDirPathSep, firstDot) == string::npos)) {
415 return boost::to_lower_copy(path.substr(firstDot + 1));
421 //------------------------------------------------------------------------------
422 void SGPath::validate() const
424 if (_cached && _cacheEnabled) {
435 bool remove_trailing = false;
436 string statPath(path);
437 if ((path.length() > 1) && (path.back() == '/')) {
441 if (_stat(statPath.c_str(), &buf ) < 0) {
445 _isFile = ((S_IFREG & buf.st_mode ) !=0);
446 _isDir = ((S_IFDIR & buf.st_mode ) !=0);
447 _modTime = buf.st_mtime;
453 if (stat(path.c_str(), &buf ) < 0) {
457 _isFile = ((S_ISREG(buf.st_mode )) != 0);
458 _isDir = ((S_ISDIR(buf.st_mode )) != 0);
459 _modTime = buf.st_mtime;
466 //------------------------------------------------------------------------------
467 void SGPath::checkAccess() const
469 if( _rwCached && _cacheEnabled )
472 if( _permission_checker )
474 Permissions p = _permission_checker(*this);
487 bool SGPath::exists() const
493 //------------------------------------------------------------------------------
494 bool SGPath::canRead() const
500 //------------------------------------------------------------------------------
501 bool SGPath::canWrite() const
507 bool SGPath::isDir() const
510 return _exists && _isDir;
513 bool SGPath::isFile() const
516 return _exists && _isFile;
519 //------------------------------------------------------------------------------
521 # define sgMkDir(d,m) _mkdir(d)
523 # define sgMkDir(d,m) mkdir(d,m)
526 int SGPath::create_dir(mode_t mode)
531 SG_WARN, "Error creating directory for '" << str() << "'"
532 " reason: access denied" );
536 string_list dirlist = sgPathSplit(dir());
537 if ( dirlist.empty() )
539 string path = dirlist[0];
540 string_list path_elements = sgPathBranchSplit(path);
541 bool absolute = !path.empty() && path[0] == sgDirPathSep;
544 SGPath dir(absolute ? string( 1, sgDirPathSep ) : "", _permission_checker);
545 dir.concat( path_elements[0] );
547 if ( dir.str().find(':') != string::npos && path_elements.size() >= 2 ) {
548 dir.append( path_elements[1] );
554 for(; (r = stat(dir.c_str(), &info)) == 0 && i < path_elements.size(); ++i)
555 dir.append(path_elements[i]);
557 return 0; // Directory already exists
561 if( sgMkDir(dir.c_str(), mode) )
564 SG_ALERT, "Error creating directory: (" << dir.str() << ")" );
568 SG_LOG(SG_IO, SG_DEBUG, "Directory created: " << dir.str());
570 if( i >= path_elements.size() )
573 dir.append(path_elements[i++]);
579 string_list sgPathBranchSplit( const string &dirpath ) {
580 string_list path_elements;
581 string element, path = dirpath;
582 while ( ! path.empty() ) {
583 size_t p = path.find( sgDirPathSep );
584 if ( p != string::npos ) {
585 element = path.substr( 0, p );
586 path.erase( 0, p + 1 );
591 if ( ! element.empty() )
592 path_elements.push_back( element );
594 return path_elements;
598 string_list sgPathSplit( const string &search_path ) {
599 string tmp = search_path;
606 int index = tmp.find(sgSearchPathSep);
608 result.push_back( tmp.substr(0, index) );
609 tmp = tmp.substr( index + 1 );
612 result.push_back( tmp );
620 bool SGPath::isAbsolute() const
627 // detect '[A-Za-z]:/'
628 if (path.size() > 2) {
629 if (isalpha(path[0]) && (path[1] == ':') && (path[2] == sgDirPathSep)) {
635 return (path[0] == sgDirPathSep);
638 bool SGPath::isNull() const
643 std::string SGPath::str_native() const
646 std::string s = str();
647 std::string::size_type pos;
648 std::string nativeSeparator;
649 nativeSeparator = sgDirPathSepBad;
651 while( (pos=s.find( sgDirPathSep )) != std::string::npos ) {
652 s.replace( pos, 1, nativeSeparator );
660 //------------------------------------------------------------------------------
661 bool SGPath::remove()
665 SG_LOG( SG_IO, SG_WARN, "file remove failed: (" << str() << ")"
666 " reason: access denied" );
670 int err = ::unlink(c_str());
673 SG_LOG( SG_IO, SG_WARN, "file remove failed: (" << str() << ") "
674 " reason: " << strerror(errno) );
675 // TODO check if failed unlink can really change any of the cached values
678 _cached = false; // stat again if required
683 time_t SGPath::modTime() const
689 bool SGPath::operator==(const SGPath& other) const
691 return (path == other.path);
694 bool SGPath::operator!=(const SGPath& other) const
696 return (path != other.path);
699 //------------------------------------------------------------------------------
700 bool SGPath::rename(const SGPath& newName)
702 if( !canRead() || !canWrite() || !newName.canWrite() )
704 SG_LOG( SG_IO, SG_WARN, "rename failed: from " << str() <<
705 " to " << newName.str() <<
706 " reason: access denied" );
711 if (newName.exists()) {
718 if( ::rename(c_str(), newName.c_str()) != 0 )
720 SG_LOG( SG_IO, SG_WARN, "rename failed: from " << str() <<
721 " to " << newName.str() <<
722 " reason: " << strerror(errno) );
728 // Do not remove permission checker (could happen for example if just using
729 // a std::string as new name)
730 if( newName._permission_checker )
731 _permission_checker = newName._permission_checker;
739 //------------------------------------------------------------------------------
740 SGPath SGPath::standardLocation(StandardLocation type, const SGPath& def)
749 if (IsWindowsVistaOrGreater())
750 return pathForKnownFolder(FOLDERID_Desktop, def);
752 return pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def);
755 if (IsWindowsVistaOrGreater())
756 return pathForKnownFolder(FOLDERID_Downloads, def);
761 return pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def);
764 if (IsWindowsVistaOrGreater())
765 return pathForKnownFolder(FOLDERID_Documents, def);
767 return pathForCSIDL(CSIDL_MYDOCUMENTS, def);
770 if (IsWindowsVistaOrGreater())
771 return pathForKnownFolder(FOLDERID_Pictures, def);
773 return pathForCSIDL(CSIDL_MYPICTURES, def);
776 // since this is C++, we can't include NSPathUtilities.h to access the enum
777 // values, so hard-coding them here (they are stable, don't worry)
779 return appleSpecialFolder(15, 1, def);
781 return appleSpecialFolder(12, 1, def);
783 return appleSpecialFolder(9, 1, def);
785 return appleSpecialFolder(19, 1, def);
788 return getXDGDir("DESKTOP", def, "Desktop");
790 return getXDGDir("DOWNLOADS", def, "Downloads");
792 return getXDGDir("DOCUMENTS", def, "Documents");
794 return getXDGDir("PICTURES", def, "Pictures");
799 "SGPath::standardLocation() unhandled type: " << type );
804 //------------------------------------------------------------------------------
805 SGPath SGPath::fromEnv(const char* name, const SGPath& def)
807 const char* val = getenv(name);
809 return SGPath(val, def._permission_checker);
813 //------------------------------------------------------------------------------
814 SGPath SGPath::home(const SGPath& def)
817 return fromEnv("USERPROFILE", def);
819 return fromEnv("HOME", def);
823 //------------------------------------------------------------------------------
824 SGPath SGPath::desktop(const SGPath& def)
826 return standardLocation(DESKTOP, def);
829 //------------------------------------------------------------------------------
830 SGPath SGPath::documents(const SGPath& def)
832 return standardLocation(DOCUMENTS, def);
835 //------------------------------------------------------------------------------
836 std::string SGPath::realpath() const
838 #if (defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED <= 1050)
839 // Workaround for Mac OS 10.5. Somehow fgfs crashes on Mac at ::realpath.
840 // This means relative paths cannot be used on Mac OS <= 10.5
843 #if defined(_MSC_VER) /*for MS compilers */ || defined(_WIN32) /*needed for non MS windows compilers like MingW*/
844 // with absPath NULL, will allocate, and ignore length
845 char *buf = _fullpath( NULL, path.c_str(), _MAX_PATH );
848 char* buf = ::realpath(path.c_str(), NULL);
852 SG_LOG(SG_IO, SG_WARN, "ERROR: The path '" << path << "' does not exist in the file system.");