]> git.mxchange.org Git - simgear.git/blob - simgear/misc/sg_path.cxx
Fix VS2010 lack of fminf
[simgear.git] / simgear / misc / sg_path.cxx
1 // sg_path.cxx -- routines to abstract out path separator differences
2 //               between MacOS and the rest of the world
3 //
4 // Written by Curtis L. Olson, started April 1999.
5 //
6 // Copyright (C) 1999  Curtis L. Olson - http://www.flightgear.org/~curt
7 //
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.
12 //
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.
17 //
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.
21 //
22 // $Id$
23
24
25 #include <simgear/compiler.h>
26
27 #include <simgear_config.h>
28 #include <simgear/debug/logstream.hxx>
29 #include <simgear/misc/strutils.hxx>
30 #include <stdio.h>
31 #include <sys/stat.h>
32 #include <errno.h>
33 #include <fstream>
34
35 #ifdef _WIN32
36 #  include <direct.h>
37 #endif
38 #include "sg_path.hxx"
39
40 #include <boost/algorithm/string/case_conv.hpp>
41
42 using std::string;
43 using simgear::strutils::starts_with;
44
45 /**
46  * define directory path separators
47  */
48
49 static const char sgDirPathSep = '/';
50 static const char sgDirPathSepBad = '\\';
51
52 #ifdef _WIN32
53 static const char sgSearchPathSep = ';';
54 #else
55 static const char sgSearchPathSep = ':';
56 #endif
57
58 #ifdef _WIN32
59 #include <ShlObj.h> // for CSIDL
60
61 static SGPath pathForCSIDL(int csidl, const SGPath& def)
62 {
63         typedef BOOL (WINAPI*GetSpecialFolderPath)(HWND, LPSTR, int, BOOL);
64         static GetSpecialFolderPath SHGetSpecialFolderPath = NULL;
65
66         // lazy open+resolve of shell32
67         if (!SHGetSpecialFolderPath) {
68                 HINSTANCE shellDll = ::LoadLibrary("shell32");
69                 SHGetSpecialFolderPath = (GetSpecialFolderPath) GetProcAddress(shellDll, "SHGetSpecialFolderPathA");
70         }
71
72         if (!SHGetSpecialFolderPath){
73                 return def;
74         }
75
76         char path[MAX_PATH];
77         if (SHGetSpecialFolderPath(0, path, csidl, false)) {
78                 return SGPath(path, def.getPermissionChecker());
79         }
80
81         return def;
82 }
83 #elif __APPLE__
84
85 // defined in CocoaHelpers.mm
86 SGPath appleSpecialFolder(int dirType, int domainMask, const SGPath& def);
87
88 #else
89 static SGPath getXDGDir( const std::string& name,
90                          const SGPath& def,
91                          const std::string& fallback )
92 {
93   // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
94
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")
100                          / "user-dirs.dirs";
101
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=\"";
106
107   std::ifstream user_dirs_file( user_dirs.c_str() );
108   std::string line;
109   while( std::getline(user_dirs_file, line).good() )
110   {
111     if( !starts_with(line, XDG_ID) || *line.rbegin() != '"' )
112       continue;
113
114     // Extract dir from XDG_<name>_DIR="<dir>"
115     line = line.substr(XDG_ID.length(), line.length() - XDG_ID.length() - 1 );
116
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()));
121
122     return SGPath(line, def.getPermissionChecker());
123   }
124
125   if( def.isNull() )
126     return SGPath::home(def) / fallback;
127
128   return def;
129 }
130 #endif
131
132 // For windows, replace "\" by "/".
133 void
134 SGPath::fix()
135 {
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;
140         }
141     }
142     // drop trailing "/"
143     while ((sz>1)&&(path[sz-1]==sgDirPathSep))
144     {
145         path.resize(--sz);
146     }
147 }
148
149
150 // default constructor
151 SGPath::SGPath(PermissionChecker validator)
152     : path(""),
153     _permission_checker(validator),
154     _cached(false),
155     _rwCached(false),
156     _cacheEnabled(true)
157 {
158 }
159
160
161 // create a path based on "path"
162 SGPath::SGPath( const std::string& p, PermissionChecker validator )
163     : path(p),
164     _permission_checker(validator),
165     _cached(false),
166     _rwCached(false),
167     _cacheEnabled(true)
168 {
169     fix();
170 }
171
172 // create a path based on "path" and a "subpath"
173 SGPath::SGPath( const SGPath& p,
174                 const std::string& r,
175                 PermissionChecker validator )
176     : path(p.path),
177     _permission_checker(validator),
178     _cached(false),
179     _rwCached(false),
180     _cacheEnabled(p._cacheEnabled)
181 {
182     append(r);
183     fix();
184 }
185
186 SGPath::SGPath(const SGPath& p) :
187   path(p.path),
188   _permission_checker(p._permission_checker),
189   _cached(p._cached),
190   _rwCached(p._rwCached),
191   _cacheEnabled(p._cacheEnabled),
192   _canRead(p._canRead),
193   _canWrite(p._canWrite),
194   _exists(p._exists),
195   _isDir(p._isDir),
196   _isFile(p._isFile),
197   _modTime(p._modTime)
198 {
199 }
200
201 SGPath& SGPath::operator=(const SGPath& p)
202 {
203   path = p.path;
204   _permission_checker = p._permission_checker,
205   _cached = p._cached;
206   _rwCached = p._rwCached;
207   _cacheEnabled = p._cacheEnabled;
208   _canRead = p._canRead;
209   _canWrite = p._canWrite;
210   _exists = p._exists;
211   _isDir = p._isDir;
212   _isFile = p._isFile;
213   _modTime = p._modTime;
214   return *this;
215 }
216
217 // destructor
218 SGPath::~SGPath() {
219 }
220
221
222 // set path
223 void SGPath::set( const string& p ) {
224     path = p;
225     fix();
226     _cached = false;
227     _rwCached = false;
228 }
229
230 //------------------------------------------------------------------------------
231 void SGPath::setPermissionChecker(PermissionChecker validator)
232 {
233   _permission_checker = validator;
234   _rwCached = false;
235 }
236
237 //------------------------------------------------------------------------------
238 SGPath::PermissionChecker SGPath::getPermissionChecker() const
239 {
240   return _permission_checker;
241 }
242
243 //------------------------------------------------------------------------------
244 void SGPath::set_cached(bool cached)
245 {
246   _cacheEnabled = cached;
247 }
248
249 // append another piece to the existing path
250 void SGPath::append( const string& p ) {
251     if ( path.empty() ) {
252         path = p;
253     } else {
254     if ( p[0] != sgDirPathSep ) {
255         path += sgDirPathSep;
256     }
257         path += p;
258     }
259     fix();
260     _cached = false;
261     _rwCached = false;
262 }
263
264 //------------------------------------------------------------------------------
265 SGPath SGPath::operator/( const std::string& p ) const
266 {
267   SGPath ret = *this;
268   ret.append(p);
269   return ret;
270 }
271
272 //add a new path component to the existing path string
273 void SGPath::add( const string& p ) {
274     append( sgSearchPathSep+p );
275 }
276
277
278 // concatenate a string to the end of the path without inserting a
279 // path separator
280 void SGPath::concat( const string& p ) {
281     if ( path.empty() ) {
282         path = p;
283     } else {
284         path += p;
285     }
286     fix();
287     _cached = false;
288     _rwCached = false;
289 }
290
291
292 // Get the file part of the path (everything after the last path sep)
293 string SGPath::file() const
294 {
295     string::size_type index = path.rfind(sgDirPathSep);
296     if (index != string::npos) {
297         return path.substr(index + 1);
298     } else {
299         return path;
300     }
301 }
302   
303
304 // get the directory part of the path.
305 string SGPath::dir() const {
306     int index = path.rfind(sgDirPathSep);
307     if (index >= 0) {
308         return path.substr(0, index);
309     } else {
310         return "";
311     }
312 }
313
314 // get the base part of the path (everything but the extension.)
315 string SGPath::base() const
316 {
317     string::size_type index = path.rfind(".");
318     string::size_type lastSep = path.rfind(sgDirPathSep);
319     
320 // tolerate dots inside directory names
321     if ((lastSep != string::npos) && (index < lastSep)) {
322         return path;
323     }
324     
325     if (index != string::npos) {
326         return path.substr(0, index);
327     } else {
328         return path;
329     }
330 }
331
332 string SGPath::file_base() const
333 {
334     string::size_type index = path.rfind(sgDirPathSep);
335     if (index == string::npos) {
336         index = 0; // no separator in the name
337     } else {
338         ++index; // skip past the separator
339     }
340     
341     string::size_type firstDot = path.find(".", index);
342     if (firstDot == string::npos) {
343         return path.substr(index); // no extensions
344     }
345     
346     return path.substr(index, firstDot - index);
347 }
348
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);
356     } else {
357         return "";
358     }
359 }
360
361 string SGPath::lower_extension() const {
362     return boost::to_lower_copy(extension());
363 }
364
365 string SGPath::complete_lower_extension() const
366 {
367     string::size_type index = path.rfind(sgDirPathSep);
368     if (index == string::npos) {
369         index = 0; // no separator in the name
370     } else {
371         ++index; // skip past the separator
372     }
373     
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));
377     } else {
378         return "";
379     }
380 }
381
382 //------------------------------------------------------------------------------
383 void SGPath::validate() const
384 {
385   if (_cached && _cacheEnabled) {
386     return;
387   }
388
389   if (path.empty()) {
390           _exists = false;
391           return;
392   }
393
394 #ifdef _WIN32
395   struct _stat buf ;
396   bool remove_trailing = false;
397   string statPath(path);
398   if ((path.length() > 1) && (path.back() == '/')) {
399           statPath.pop_back();
400   }
401       
402   if (_stat(statPath.c_str(), &buf ) < 0) {
403     _exists = false;
404   } else {
405     _exists = true;
406     _isFile = ((S_IFREG & buf.st_mode ) !=0);
407     _isDir = ((S_IFDIR & buf.st_mode ) !=0);
408     _modTime = buf.st_mtime;
409   }
410
411 #else
412   struct stat buf ;
413
414   if (stat(path.c_str(), &buf ) < 0) {
415     _exists = false;
416   } else {
417     _exists = true;
418     _isFile = ((S_ISREG(buf.st_mode )) != 0);
419     _isDir = ((S_ISDIR(buf.st_mode )) != 0);
420     _modTime = buf.st_mtime;
421   }
422   
423 #endif
424   _cached = true;
425 }
426
427 //------------------------------------------------------------------------------
428 void SGPath::checkAccess() const
429 {
430   if( _rwCached && _cacheEnabled )
431     return;
432
433   if( _permission_checker )
434   {
435     Permissions p = _permission_checker(*this);
436     _canRead = p.read;
437     _canWrite = p.write;
438   }
439   else
440   {
441     _canRead = true;
442     _canWrite = true;
443   }
444
445   _rwCached = true;
446 }
447
448 bool SGPath::exists() const
449 {
450   validate();
451   return _exists;
452 }
453
454 //------------------------------------------------------------------------------
455 bool SGPath::canRead() const
456 {
457   checkAccess();
458   return _canRead;
459 }
460
461 //------------------------------------------------------------------------------
462 bool SGPath::canWrite() const
463 {
464   checkAccess();
465   return _canWrite;
466 }
467
468 bool SGPath::isDir() const
469 {
470   validate();
471   return _exists && _isDir;
472 }
473
474 bool SGPath::isFile() const
475 {
476   validate();
477   return _exists && _isFile;
478 }
479
480 //------------------------------------------------------------------------------
481 #ifdef _WIN32
482 #  define sgMkDir(d,m)       _mkdir(d)
483 #else
484 #  define sgMkDir(d,m)       mkdir(d,m)
485 #endif
486
487 int SGPath::create_dir(mode_t mode)
488 {
489   if( !canWrite() )
490   {
491     SG_LOG( SG_IO,
492             SG_WARN, "Error creating directory for '" << str() << "'"
493                                                     " reason: access denied" );
494     return -3;
495   }
496
497     string_list dirlist = sgPathSplit(dir());
498     if ( dirlist.empty() )
499         return -1;
500     string path = dirlist[0];
501     string_list path_elements = sgPathBranchSplit(path);
502     bool absolute = !path.empty() && path[0] == sgDirPathSep;
503
504     unsigned int i = 1;
505     SGPath dir(absolute ? string( 1, sgDirPathSep ) : "", _permission_checker);
506     dir.concat( path_elements[0] );
507 #ifdef _WIN32
508     if ( dir.str().find(':') != string::npos && path_elements.size() >= 2 ) {
509         dir.append( path_elements[1] );
510         i = 2;
511     }
512 #endif
513   struct stat info;
514   int r;
515   for(; (r = stat(dir.c_str(), &info)) == 0 && i < path_elements.size(); ++i)
516     dir.append(path_elements[i]);
517   if( r == 0 )
518       return 0; // Directory already exists
519
520   for(;;)
521   {
522     if( sgMkDir(dir.c_str(), mode) )
523     {
524       SG_LOG( SG_IO,
525               SG_ALERT, "Error creating directory: (" << dir.str() << ")" );
526       return -2;
527     }
528     else
529       SG_LOG(SG_IO, SG_DEBUG, "Directory created: " << dir.str());
530
531     if( i >= path_elements.size() )
532       return 0;
533
534     dir.append(path_elements[i++]);
535   }
536
537   return 0;
538 }
539
540 string_list sgPathBranchSplit( const string &dirpath ) {
541     string_list path_elements;
542     string element, path = dirpath;
543     while ( ! path.empty() ) {
544         size_t p = path.find( sgDirPathSep );
545         if ( p != string::npos ) {
546             element = path.substr( 0, p );
547             path.erase( 0, p + 1 );
548         } else {
549             element = path;
550             path = "";
551         }
552         if ( ! element.empty() )
553             path_elements.push_back( element );
554     }
555     return path_elements;
556 }
557
558
559 string_list sgPathSplit( const string &search_path ) {
560     string tmp = search_path;
561     string_list result;
562     result.clear();
563
564     bool done = false;
565
566     while ( !done ) {
567         int index = tmp.find(sgSearchPathSep);
568         if (index >= 0) {
569             result.push_back( tmp.substr(0, index) );
570             tmp = tmp.substr( index + 1 );
571         } else {
572             if ( !tmp.empty() )
573                 result.push_back( tmp );
574             done = true;
575         }
576     }
577
578     return result;
579 }
580
581 bool SGPath::isAbsolute() const
582 {
583   if (path.empty()) {
584     return false;
585   }
586   
587 #ifdef _WIN32
588   // detect '[A-Za-z]:/'
589   if (path.size() > 2) {
590     if (isalpha(path[0]) && (path[1] == ':') && (path[2] == sgDirPathSep)) {
591       return true;
592     }
593   }
594 #endif
595   
596   return (path[0] == sgDirPathSep);
597 }
598
599 bool SGPath::isNull() const
600 {
601   return path.empty();
602 }
603
604 std::string SGPath::str_native() const
605 {
606 #ifdef _WIN32
607     std::string s = str();
608     std::string::size_type pos;
609     std::string nativeSeparator;
610     nativeSeparator = sgDirPathSepBad;
611
612     while( (pos=s.find( sgDirPathSep )) != std::string::npos ) {
613         s.replace( pos, 1, nativeSeparator );
614     }
615     return s;
616 #else
617     return str();
618 #endif
619 }
620
621 //------------------------------------------------------------------------------
622 bool SGPath::remove()
623 {
624   if( !canWrite() )
625   {
626     SG_LOG( SG_IO, SG_WARN, "file remove failed: (" << str() << ")"
627                                                " reason: access denied" );
628     return false;
629   }
630
631   int err = ::unlink(c_str());
632   if( err )
633   {
634     SG_LOG( SG_IO, SG_WARN, "file remove failed: (" << str() << ") "
635                                                " reason: " << strerror(errno) );
636     // TODO check if failed unlink can really change any of the cached values
637   }
638
639   _cached = false; // stat again if required
640   _rwCached = false;
641   return (err == 0);
642 }
643
644 time_t SGPath::modTime() const
645 {
646     validate();
647     return _modTime;
648 }
649
650 bool SGPath::operator==(const SGPath& other) const
651 {
652     return (path == other.path);
653 }
654
655 bool SGPath::operator!=(const SGPath& other) const
656 {
657     return (path != other.path);
658 }
659
660 //------------------------------------------------------------------------------
661 bool SGPath::rename(const SGPath& newName)
662 {
663   if( !canRead() || !canWrite() || !newName.canWrite() )
664   {
665     SG_LOG( SG_IO, SG_WARN, "rename failed: from " << str() <<
666                                             " to " << newName.str() <<
667                                             " reason: access denied" );
668     return false;
669   }
670
671 #ifdef SG_WINDOWS
672         if (newName.exists()) {
673                 SGPath r(newName);
674                 if (!r.remove()) {
675                         return false;
676                 }
677         }
678 #endif
679   if( ::rename(c_str(), newName.c_str()) != 0 )
680   {
681     SG_LOG( SG_IO, SG_WARN, "rename failed: from " << str() <<
682                                             " to " << newName.str() <<
683                                             " reason: " << strerror(errno) );
684     return false;
685   }
686
687   path = newName.path;
688
689   // Do not remove permission checker (could happen for example if just using
690   // a std::string as new name)
691   if( newName._permission_checker )
692     _permission_checker = newName._permission_checker;
693
694   _cached = false;
695   _rwCached = false;
696
697   return true;
698 }
699
700 //------------------------------------------------------------------------------
701 SGPath SGPath::standardLocation(StandardLocation type, const SGPath& def)
702 {
703   switch(type)
704   {
705     case HOME:
706       return home(def);
707 #ifdef _WIN32
708     case DESKTOP:
709       return pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def);
710     case DOWNLOADS:
711       // TODO use KnownFolders
712       // http://msdn.microsoft.com/en-us/library/bb776911%28v=vs.85%29.aspx
713       if( !def.isNull() )
714         return def;
715
716       return pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def);
717     case DOCUMENTS:
718       return pathForCSIDL(CSIDL_MYDOCUMENTS, def);
719     case PICTURES:
720       return pathForCSIDL(CSIDL_MYPICTURES, def);
721 #elif __APPLE__
722       // since this is C++, we can't include NSPathUtilities.h to access the enum
723       // values, so hard-coding them here (they are stable, don't worry)
724     case DOWNLOADS:
725       return appleSpecialFolder(15, 1, def);
726     case DESKTOP:
727       return appleSpecialFolder(12, 1, def);
728     case DOCUMENTS:
729       return appleSpecialFolder(9, 1, def);
730     case PICTURES:
731       return appleSpecialFolder(19, 1, def);
732 #else
733     case DESKTOP:
734       return getXDGDir("DESKTOP", def, "Desktop");
735     case DOWNLOADS:
736       return getXDGDir("DOWNLOADS", def, "Downloads");
737     case DOCUMENTS:
738       return getXDGDir("DOCUMENTS", def, "Documents");
739     case PICTURES:
740       return getXDGDir("PICTURES", def, "Pictures");
741 #endif
742     default:
743       SG_LOG( SG_GENERAL,
744               SG_WARN,
745               "SGPath::standardLocation() unhandled type: " << type );
746       return def;
747   }
748 }
749
750 //------------------------------------------------------------------------------
751 SGPath SGPath::fromEnv(const char* name, const SGPath& def)
752 {
753   const char* val = getenv(name);
754   if( val && val[0] )
755     return SGPath(val, def._permission_checker);
756   return def;
757 }
758
759 #ifdef _WIN32
760 //------------------------------------------------------------------------------
761 SGPath SGPath::home(const SGPath& def)
762 {
763   // TODO
764   return def;
765 }
766 #else
767 //------------------------------------------------------------------------------
768 SGPath SGPath::home(const SGPath& def)
769 {
770   return fromEnv("HOME", def);
771 }
772 #endif
773
774 //------------------------------------------------------------------------------
775 SGPath SGPath::desktop(const SGPath& def)
776 {
777   return standardLocation(DESKTOP, def);
778 }
779
780 //------------------------------------------------------------------------------
781 SGPath SGPath::documents(const SGPath& def)
782 {
783   return standardLocation(DOCUMENTS, def);
784 }
785
786 //------------------------------------------------------------------------------
787 std::string SGPath::realpath() const
788 {
789 #if (defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED <= 1050)
790     // Workaround for Mac OS 10.5. Somehow fgfs crashes on Mac at ::realpath. 
791     // This means relative paths cannot be used on Mac OS <= 10.5
792     return path;
793 #else
794   #if defined(_MSC_VER) /*for MS compilers */ || defined(_WIN32) /*needed for non MS windows compilers like MingW*/
795     // with absPath NULL, will allocate, and ignore length
796     char *buf = _fullpath( NULL, path.c_str(), _MAX_PATH );
797   #else
798     // POSIX
799     char* buf = ::realpath(path.c_str(), NULL);
800   #endif
801     if (!buf)
802     {
803         SG_LOG(SG_IO, SG_ALERT, "ERROR: The path '" << path << "' does not exist in the file system.");
804         return path;
805     }
806     std::string p(buf);
807     free(buf);
808     return p;
809 #endif
810 }