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
86 // create a path based on "path"
87 SGPath::SGPath( const std::string& p )
95 // create a path based on "path" and a "subpath"
96 SGPath::SGPath( const SGPath& p, const std::string& r )
99 _cacheEnabled(p._cacheEnabled)
105 SGPath::SGPath(const SGPath& p) :
108 _cacheEnabled(p._cacheEnabled),
116 SGPath& SGPath::operator=(const SGPath& p)
120 _cacheEnabled = p._cacheEnabled;
124 _modTime = p._modTime;
134 void SGPath::set( const string& p ) {
140 void SGPath::set_cached(bool cached)
142 _cacheEnabled = cached;
145 // append another piece to the existing path
146 void SGPath::append( const string& p ) {
147 if ( path.empty() ) {
150 if ( p[0] != sgDirPathSep ) {
151 path += sgDirPathSep;
159 //------------------------------------------------------------------------------
160 SGPath SGPath::operator/( const std::string& p ) const
167 //add a new path component to the existing path string
168 void SGPath::add( const string& p ) {
169 append( sgSearchPathSep+p );
173 // concatenate a string to the end of the path without inserting a
175 void SGPath::concat( const string& p ) {
176 if ( path.empty() ) {
186 // Get the file part of the path (everything after the last path sep)
187 string SGPath::file() const
189 string::size_type index = path.rfind(sgDirPathSep);
190 if (index != string::npos) {
191 return path.substr(index + 1);
198 // get the directory part of the path.
199 string SGPath::dir() const {
200 int index = path.rfind(sgDirPathSep);
202 return path.substr(0, index);
208 // get the base part of the path (everything but the extension.)
209 string SGPath::base() const
211 string::size_type index = path.rfind(".");
212 string::size_type lastSep = path.rfind(sgDirPathSep);
214 // tolerate dots inside directory names
215 if ((lastSep != string::npos) && (index < lastSep)) {
219 if (index != string::npos) {
220 return path.substr(0, index);
226 string SGPath::file_base() const
228 string::size_type index = path.rfind(sgDirPathSep);
229 if (index == string::npos) {
230 index = 0; // no separator in the name
232 ++index; // skip past the separator
235 string::size_type firstDot = path.find(".", index);
236 if (firstDot == string::npos) {
237 return path.substr(index); // no extensions
240 return path.substr(index, firstDot - index);
243 // get the extension (everything after the final ".")
244 // but make sure no "/" follows the "." character (otherwise it
245 // is has to be a directory name containing a ".").
246 string SGPath::extension() const {
247 int index = path.rfind(".");
248 if ((index >= 0) && (path.find("/", index) == string::npos)) {
249 return path.substr(index + 1);
255 string SGPath::lower_extension() const {
256 return boost::to_lower_copy(extension());
259 string SGPath::complete_lower_extension() 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) && (path.find(sgDirPathSep, firstDot) == string::npos)) {
270 return boost::to_lower_copy(path.substr(firstDot + 1));
276 void SGPath::validate() const
278 if (_cached && _cacheEnabled) {
285 bool remove_trailing = false;
286 if ( path.length() > 1 && path[path.length()-1] == '/' )
287 remove_trailing=true;
288 if (_stat (path.substr(0,remove_trailing?path.length()-1:path.length()).c_str(), &buf ) < 0) {
292 _isFile = ((S_IFREG & buf.st_mode ) !=0);
293 _isDir = ((S_IFDIR & buf.st_mode ) !=0);
294 _modTime = buf.st_mtime;
300 if (stat(path.c_str(), &buf ) < 0) {
304 _isFile = ((S_ISREG(buf.st_mode )) != 0);
305 _isDir = ((S_ISDIR(buf.st_mode )) != 0);
306 _modTime = buf.st_mtime;
313 bool SGPath::exists() const
319 bool SGPath::isDir() const
322 return _exists && _isDir;
325 bool SGPath::isFile() const
328 return _exists && _isFile;
332 # define sgMkDir(d,m) _mkdir(d)
334 # define sgMkDir(d,m) mkdir(d,m)
338 int SGPath::create_dir( mode_t mode ) {
339 string_list dirlist = sgPathSplit(dir());
340 if ( dirlist.empty() )
342 string path = dirlist[0];
343 string_list path_elements = sgPathBranchSplit(path);
344 bool absolute = !path.empty() && path[0] == sgDirPathSep;
347 SGPath dir = absolute ? string( 1, sgDirPathSep ) : "";
348 dir.concat( path_elements[0] );
350 if ( dir.str().find(':') != string::npos && path_elements.size() >= 2 ) {
351 dir.append( path_elements[1] );
357 for(; ( r = stat( dir.c_str(), &info ) ) == 0 && i < path_elements.size(); i++) {
358 dir.append(path_elements[i]);
361 return 0; // Directory already exists
363 if ( sgMkDir( dir.c_str(), mode) ) {
364 SG_LOG( SG_IO, SG_ALERT, "Error creating directory: " + dir.str() );
367 for(; i < path_elements.size(); i++) {
368 dir.append(path_elements[i]);
369 if ( sgMkDir( dir.c_str(), mode) ) {
370 SG_LOG( SG_IO, SG_ALERT, "Error creating directory: " + dir.str() );
378 string_list sgPathBranchSplit( const string &dirpath ) {
379 string_list path_elements;
380 string element, path = dirpath;
381 while ( ! path.empty() ) {
382 size_t p = path.find( sgDirPathSep );
383 if ( p != string::npos ) {
384 element = path.substr( 0, p );
385 path.erase( 0, p + 1 );
390 if ( ! element.empty() )
391 path_elements.push_back( element );
393 return path_elements;
397 string_list sgPathSplit( const string &search_path ) {
398 string tmp = search_path;
405 int index = tmp.find(sgSearchPathSep);
407 result.push_back( tmp.substr(0, index) );
408 tmp = tmp.substr( index + 1 );
411 result.push_back( tmp );
419 bool SGPath::isAbsolute() const
426 // detect '[A-Za-z]:/'
427 if (path.size() > 2) {
428 if (isalpha(path[0]) && (path[1] == ':') && (path[2] == sgDirPathSep)) {
434 return (path[0] == sgDirPathSep);
437 bool SGPath::isNull() const
442 std::string SGPath::str_native() const
445 std::string s = str();
446 std::string::size_type pos;
447 std::string nativeSeparator;
448 nativeSeparator = sgDirPathSepBad;
450 while( (pos=s.find( sgDirPathSep )) != std::string::npos ) {
451 s.replace( pos, 1, nativeSeparator );
459 bool SGPath::remove()
461 int err = ::unlink(c_str());
463 SG_LOG(SG_IO, SG_WARN, "file remove failed: (" << str() << ") " << strerror(errno));
468 time_t SGPath::modTime() const
474 bool SGPath::operator==(const SGPath& other) const
476 return (path == other.path);
479 bool SGPath::operator!=(const SGPath& other) const
481 return (path != other.path);
484 bool SGPath::rename(const SGPath& newName)
486 if (::rename(c_str(), newName.c_str()) != 0) {
487 SG_LOG(SG_IO, SG_WARN, "renamed failed: from " << str() << " to " << newName.str()
488 << " reason: " << strerror(errno));
497 //------------------------------------------------------------------------------
498 SGPath SGPath::fromEnv(const char* name, const SGPath& def)
500 const char* val = getenv(name);
507 //------------------------------------------------------------------------------
508 SGPath SGPath::home()
514 //------------------------------------------------------------------------------
515 SGPath SGPath::home()
517 return fromEnv("HOME");
523 #include <ShlObj.h> // for CSIDL
525 //------------------------------------------------------------------------------
526 SGPath SGPath::desktop()
528 typedef BOOL (WINAPI*GetSpecialFolderPath)(HWND, LPSTR, int, BOOL);
529 static GetSpecialFolderPath SHGetSpecialFolderPath = NULL;
531 // lazy open+resolve of shell32
532 if (!SHGetSpecialFolderPath) {
533 HINSTANCE shellDll = ::LoadLibrary("shell32");
534 SHGetSpecialFolderPath = (GetSpecialFolderPath) GetProcAddress(shellDll, "SHGetSpecialFolderPathA");
537 if (!SHGetSpecialFolderPath){
542 if (SHGetSpecialFolderPath(0, path, CSIDL_DESKTOPDIRECTORY, false)) {
546 SG_LOG(SG_GENERAL, SG_ALERT, "SGPath::desktop() failed, bad" );
550 #include <CoreServices/CoreServices.h>
552 //------------------------------------------------------------------------------
553 SGPath SGPath::desktop()
556 OSErr err = FSFindFolder(kUserDomain, kDesktopFolderType, false, &ref);
561 unsigned char path[1024];
562 if (FSRefMakePath(&ref, path, 1024) != noErr) {
566 return SGPath((const char*) path);
569 //------------------------------------------------------------------------------
570 SGPath SGPath::desktop()
572 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
574 // $XDG_CONFIG_HOME defines the base directory relative to which user specific
575 // configuration files should be stored. If $XDG_CONFIG_HOME is either not set
576 // or empty, a default equal to $HOME/.config should be used.
577 const SGPath user_dirs = fromEnv("XDG_CONFIG_HOME", home() / ".config")
580 // Format is XDG_xxx_DIR="$HOME/yyy", where yyy is a shell-escaped
581 // homedir-relative path, or XDG_xxx_DIR="/yyy", where /yyy is an absolute
582 // path. No other format is supported.
583 const std::string DESKTOP = "XDG_DESKTOP_DIR=\"";
585 std::ifstream user_dirs_file( user_dirs.c_str() );
587 while( std::getline(user_dirs_file, line).good() )
589 if( !starts_with(line, DESKTOP) || *line.rbegin() != '"' )
592 // Extract dir from XDG_DESKTOP_DIR="<dir>"
593 line = line.substr(DESKTOP.length(), line.length() - DESKTOP.length() - 1 );
595 const std::string HOME = "$HOME";
596 if( starts_with(line, HOME) )
597 return home() / simgear::strutils::unescape(line.substr(HOME.length()));
602 return home() / "Desktop";
606 std::string SGPath::realpath() const
608 #if (defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED <= 1050)
609 // Workaround for Mac OS 10.5. Somehow fgfs crashes on Mac at ::realpath.
610 // This means relative paths cannot be used on Mac OS <= 10.5
613 #if defined(_MSC_VER) /*for MS compilers */ || defined(_WIN32) /*needed for non MS windows compilers like MingW*/
614 // with absPath NULL, will allocate, and ignore length
615 char *buf = _fullpath( NULL, path.c_str(), _MAX_PATH );
618 char* buf = ::realpath(path.c_str(), NULL);
622 SG_LOG(SG_IO, SG_ALERT, "ERROR: The path '" << path << "' does not exist in the file system.");