]> git.mxchange.org Git - simgear.git/blobdiff - simgear/misc/sg_path.cxx
Fix #1783: repeated error message on console
[simgear.git] / simgear / misc / sg_path.cxx
index adc4df5b50b8739db0d9d3d876fd00ba19525308..8255fa6aab742fdd11c519a64c22b39f8d820d4d 100644 (file)
@@ -56,10 +56,12 @@ static const char sgSearchPathSep = ':';
 #endif
 
 #ifdef _WIN32
+#include <ShlObj.h>         // for CSIDL
+// TODO: replace this include file with the official <versionhelpers.h> header
+// included in the Windows 8.1 SDK
+#include "sgversionhelpers.hxx"
 
-#include <ShlObj.h> // for CSIDL
-
-static SGPath pathForCSIDL(int csidl, const SGPath::PermissonChecker& checker)
+static SGPath pathForCSIDL(int csidl, const SGPath& def)
 {
        typedef BOOL (WINAPI*GetSpecialFolderPath)(HWND, LPSTR, int, BOOL);
        static GetSpecialFolderPath SHGetSpecialFolderPath = NULL;
@@ -71,17 +73,99 @@ static SGPath pathForCSIDL(int csidl, const SGPath::PermissonChecker& checker)
        }
 
        if (!SHGetSpecialFolderPath){
-               return SGPath();
+               return def;
        }
 
        char path[MAX_PATH];
        if (SHGetSpecialFolderPath(0, path, csidl, false)) {
-               return SGPath(path, checker);
+               return SGPath(path, def.getPermissionChecker());
        }
 
-       return SGPath();
+       return def;
 }
 
+static SGPath pathForKnownFolder(REFKNOWNFOLDERID folderId, const SGPath& def)
+{
+    typedef HRESULT (WINAPI*PSHGKFP)(REFKNOWNFOLDERID, DWORD, HANDLE, PWSTR*);
+
+    HINSTANCE shellDll = LoadLibrary(TEXT("shell32"));
+    if (shellDll != NULL) {
+        PSHGKFP pSHGetKnownFolderPath = (PSHGKFP) GetProcAddress(shellDll, "SHGetKnownFolderPath");
+        if (pSHGetKnownFolderPath != NULL) {
+            // system call will allocate dynamic memory... which we must release when done
+            wchar_t* localFolder = 0;
+
+            if (pSHGetKnownFolderPath(folderId, KF_FLAG_DEFAULT_PATH, NULL, &localFolder) == S_OK) {
+                // copy into local memory
+                char path[MAX_PATH];
+                size_t len;
+                if (wcstombs_s(&len, path, localFolder, MAX_PATH) != S_OK) {
+                    path[0] = '\0';
+                    SG_LOG(SG_GENERAL, SG_WARN, "WCS to MBS failed");
+                }
+
+                SGPath folder_path = SGPath(path, def.getPermissionChecker());
+
+                // release dynamic memory
+                CoTaskMemFree(static_cast<void*>(localFolder));
+
+                return folder_path;
+            }
+        }
+
+        FreeLibrary(shellDll);
+    }
+
+    return def;
+}
+
+#elif __APPLE__
+
+// defined in CocoaHelpers.mm
+SGPath appleSpecialFolder(int dirType, int domainMask, const SGPath& def);
+
+#else
+static SGPath getXDGDir( const std::string& name,
+                         const SGPath& def,
+                         const std::string& fallback )
+{
+  // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
+
+  // $XDG_CONFIG_HOME defines the base directory relative to which user specific
+  // configuration files should be stored. If $XDG_CONFIG_HOME is either not set
+  // or empty, a default equal to $HOME/.config should be used.
+  const SGPath user_dirs = SGPath::fromEnv( "XDG_CONFIG_HOME",
+                                            SGPath::home() / ".config")
+                         / "user-dirs.dirs";
+
+  // Format is XDG_xxx_DIR="$HOME/yyy", where yyy is a shell-escaped
+  // homedir-relative path, or XDG_xxx_DIR="/yyy", where /yyy is an absolute
+  // path. No other format is supported.
+  const std::string XDG_ID = "XDG_" + name + "_DIR=\"";
+
+  std::ifstream user_dirs_file( user_dirs.c_str() );
+  std::string line;
+  while( std::getline(user_dirs_file, line).good() )
+  {
+    if( !starts_with(line, XDG_ID) || *line.rbegin() != '"' )
+      continue;
+
+    // Extract dir from XDG_<name>_DIR="<dir>"
+    line = line.substr(XDG_ID.length(), line.length() - XDG_ID.length() - 1 );
+
+    const std::string HOME = "$HOME";
+    if( starts_with(line, HOME) )
+      return SGPath::home(def)
+           / simgear::strutils::unescape(line.substr(HOME.length()));
+
+    return SGPath(line, def.getPermissionChecker());
+  }
+
+  if( def.isNull() )
+    return SGPath::home(def) / fallback;
+
+  return def;
+}
 #endif
 
 // For windows, replace "\" by "/".
@@ -103,7 +187,7 @@ SGPath::fix()
 
 
 // default constructor
-SGPath::SGPath(PermissonChecker validator)
+SGPath::SGPath(PermissionChecker validator)
     : path(""),
     _permission_checker(validator),
     _cached(false),
@@ -114,7 +198,7 @@ SGPath::SGPath(PermissonChecker validator)
 
 
 // create a path based on "path"
-SGPath::SGPath( const std::string& p, PermissonChecker validator )
+SGPath::SGPath( const std::string& p, PermissionChecker validator )
     : path(p),
     _permission_checker(validator),
     _cached(false),
@@ -127,7 +211,7 @@ SGPath::SGPath( const std::string& p, PermissonChecker validator )
 // create a path based on "path" and a "subpath"
 SGPath::SGPath( const SGPath& p,
                 const std::string& r,
-                PermissonChecker validator )
+                PermissionChecker validator )
     : path(p.path),
     _permission_checker(validator),
     _cached(false),
@@ -183,14 +267,14 @@ void SGPath::set( const string& p ) {
 }
 
 //------------------------------------------------------------------------------
-void SGPath::setPermissonChecker(PermissonChecker validator)
+void SGPath::setPermissionChecker(PermissionChecker validator)
 {
   _permission_checker = validator;
   _rwCached = false;
 }
 
 //------------------------------------------------------------------------------
-SGPath::PermissonChecker SGPath::getPermissonChecker() const
+SGPath::PermissionChecker SGPath::getPermissionChecker() const
 {
   return _permission_checker;
 }
@@ -334,6 +418,7 @@ string SGPath::complete_lower_extension() const
     }
 }
 
+//------------------------------------------------------------------------------
 void SGPath::validate() const
 {
   if (_cached && _cacheEnabled) {
@@ -378,6 +463,7 @@ void SGPath::validate() const
   _cached = true;
 }
 
+//------------------------------------------------------------------------------
 void SGPath::checkAccess() const
 {
   if( _rwCached && _cacheEnabled )
@@ -430,14 +516,23 @@ bool SGPath::isFile() const
   return _exists && _isFile;
 }
 
+//------------------------------------------------------------------------------
 #ifdef _WIN32
 #  define sgMkDir(d,m)       _mkdir(d)
 #else
 #  define sgMkDir(d,m)       mkdir(d,m)
 #endif
 
+int SGPath::create_dir(mode_t mode)
+{
+  if( !canWrite() )
+  {
+    SG_LOG( SG_IO,
+            SG_WARN, "Error creating directory for '" << str() << "'"
+                                                    " reason: access denied" );
+    return -3;
+  }
 
-int SGPath::create_dir( mode_t mode ) {
     string_list dirlist = sgPathSplit(dir());
     if ( dirlist.empty() )
         return -1;
@@ -454,37 +549,31 @@ int SGPath::create_dir( mode_t mode ) {
         i = 2;
     }
 #endif
-    struct stat info;
-    int r;
-    for(; ( r = stat( dir.c_str(), &info ) ) == 0 && i < path_elements.size(); i++) {
-        dir.append(path_elements[i]);
-    }
-    if ( r == 0 ) {
-        return 0; // Directory already exists
-    }
-    for(;;)
+  struct stat info;
+  int r;
+  for(; (r = stat(dir.c_str(), &info)) == 0 && i < path_elements.size(); ++i)
+    dir.append(path_elements[i]);
+  if( r == 0 )
+      return 0; // Directory already exists
+
+  for(;;)
+  {
+    if( sgMkDir(dir.c_str(), mode) )
     {
-      if( !dir.canWrite() )
-      {
-        SG_LOG( SG_IO,
-                SG_WARN, "Error creating directory: (" << dir.str() << ")" <<
-                                                  " reason: access denied" );
-        return -3;
-      }
-      else if( sgMkDir(dir.c_str(), mode) )
-      {
-        SG_LOG( SG_IO,
-                SG_ALERT, "Error creating directory: (" << dir.str() << ")" );
-        return -2;
-      }
-
-      if( i >= path_elements.size() )
-        return  0;
-
-      dir.append(path_elements[i++]);
+      SG_LOG( SG_IO,
+              SG_ALERT, "Error creating directory: (" << dir.str() << ")" );
+      return -2;
     }
+    else
+      SG_LOG(SG_IO, SG_DEBUG, "Directory created: " << dir.str());
 
-    return 0;
+    if( i >= path_elements.size() )
+      return 0;
+
+    dir.append(path_elements[i++]);
+  }
+
+  return 0;
 }
 
 string_list sgPathBranchSplit( const string &dirpath ) {
@@ -647,6 +736,71 @@ bool SGPath::rename(const SGPath& newName)
   return true;
 }
 
+//------------------------------------------------------------------------------
+SGPath SGPath::standardLocation(StandardLocation type, const SGPath& def)
+{
+  switch(type)
+  {
+    case HOME:
+      return home(def);
+
+#ifdef _WIN32
+    case DESKTOP:
+        if (IsWindowsVistaOrGreater())
+            return pathForKnownFolder(FOLDERID_Desktop, def);
+
+        return pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def);
+
+    case DOWNLOADS:
+        if (IsWindowsVistaOrGreater())
+            return pathForKnownFolder(FOLDERID_Downloads, def);
+
+        if (!def.isNull())
+            return def;
+
+        return pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def);
+
+    case DOCUMENTS:
+        if (IsWindowsVistaOrGreater())
+            return pathForKnownFolder(FOLDERID_Documents, def);
+
+        return pathForCSIDL(CSIDL_MYDOCUMENTS, def);
+
+    case PICTURES:
+        if (IsWindowsVistaOrGreater())
+            return pathForKnownFolder(FOLDERID_Pictures, def);
+
+        return pathForCSIDL(CSIDL_MYPICTURES, def);
+
+#elif __APPLE__
+      // since this is C++, we can't include NSPathUtilities.h to access the enum
+      // values, so hard-coding them here (they are stable, don't worry)
+    case DOWNLOADS:
+      return appleSpecialFolder(15, 1, def);
+    case DESKTOP:
+      return appleSpecialFolder(12, 1, def);
+    case DOCUMENTS:
+      return appleSpecialFolder(9, 1, def);
+    case PICTURES:
+      return appleSpecialFolder(19, 1, def);
+#else
+    case DESKTOP:
+      return getXDGDir("DESKTOP", def, "Desktop");
+    case DOWNLOADS:
+      return getXDGDir("DOWNLOADS", def, "Downloads");
+    case DOCUMENTS:
+      return getXDGDir("DOCUMENTS", def, "Documents");
+    case PICTURES:
+      return getXDGDir("PICTURES", def, "Pictures");
+#endif
+    default:
+      SG_LOG( SG_GENERAL,
+              SG_WARN,
+              "SGPath::standardLocation() unhandled type: " << type );
+      return def;
+  }
+}
+
 //------------------------------------------------------------------------------
 SGPath SGPath::fromEnv(const char* name, const SGPath& def)
 {
@@ -656,99 +810,29 @@ SGPath SGPath::fromEnv(const char* name, const SGPath& def)
   return def;
 }
 
-#ifdef _WIN32
 //------------------------------------------------------------------------------
 SGPath SGPath::home(const SGPath& def)
 {
-  // TODO
-  return def;
-}
+#ifdef _WIN32
+    return fromEnv("USERPROFILE", def);
 #else
-//------------------------------------------------------------------------------
-SGPath SGPath::home(const SGPath& def)
-{
-  return fromEnv("HOME", def);
-}
+    return fromEnv("HOME", def);
 #endif
+}
 
-#ifdef _WIN32
 //------------------------------------------------------------------------------
 SGPath SGPath::desktop(const SGPath& def)
 {
-       SGPath r = pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def._permission_checker);
-       if (!r.isNull()) {
-               return r;
-       }
-
-       SG_LOG(SG_GENERAL, SG_ALERT, "SGPath::desktop() failed, bad" );
-       return def;
+  return standardLocation(DESKTOP, def);
 }
 
+//------------------------------------------------------------------------------
 SGPath SGPath::documents(const SGPath& def)
 {
-       SGPath r = pathForCSIDL(CSIDL_MYDOCUMENTS, def._permission_checker);
-       if (!r.isNull()) {
-               return r;
-       }
-
-       SG_LOG(SG_GENERAL, SG_ALERT, "SGPath::documents() failed, bad" );
-       return def;
+  return standardLocation(DOCUMENTS, def);
 }
-#elif __APPLE__
-#include <CoreServices/CoreServices.h>
 
 //------------------------------------------------------------------------------
-SGPath SGPath::desktop(const SGPath& def)
-{
-  FSRef ref;
-  OSErr err = FSFindFolder(kUserDomain, kDesktopFolderType, false, &ref);
-  if (err)
-    return def;
-
-  unsigned char path[1024];
-  if (FSRefMakePath(&ref, path, 1024) != noErr)
-      return def;
-
-  return SGPath((const char*) path, def._permission_checker);
-}
-#else
-//------------------------------------------------------------------------------
-SGPath SGPath::desktop(const SGPath& def)
-{
-  // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
-
-  // $XDG_CONFIG_HOME defines the base directory relative to which user specific
-  // configuration files should be stored. If $XDG_CONFIG_HOME is either not set
-  // or empty, a default equal to $HOME/.config should be used.
-  const SGPath user_dirs = fromEnv("XDG_CONFIG_HOME", home() / ".config")
-                         / "user-dirs.dirs";
-
-  // Format is XDG_xxx_DIR="$HOME/yyy", where yyy is a shell-escaped
-  // homedir-relative path, or XDG_xxx_DIR="/yyy", where /yyy is an absolute
-  // path. No other format is supported.
-  const std::string DESKTOP = "XDG_DESKTOP_DIR=\"";
-
-  std::ifstream user_dirs_file( user_dirs.c_str() );
-  std::string line;
-  while( std::getline(user_dirs_file, line).good() )
-  {
-    if( !starts_with(line, DESKTOP) || *line.rbegin() != '"' )
-      continue;
-
-    // Extract dir from XDG_DESKTOP_DIR="<dir>"
-    line = line.substr(DESKTOP.length(), line.length() - DESKTOP.length() - 1 );
-
-    const std::string HOME = "$HOME";
-    if( starts_with(line, HOME) )
-      return home(def) / simgear::strutils::unescape(line.substr(HOME.length()));
-
-    return SGPath(line, def._permission_checker);
-  }
-
-  return home(def) / "Desktop";
-}
-#endif
-
 std::string SGPath::realpath() const
 {
 #if (defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED <= 1050)
@@ -765,7 +849,7 @@ std::string SGPath::realpath() const
   #endif
     if (!buf)
     {
-        SG_LOG(SG_IO, SG_ALERT, "ERROR: The path '" << path << "' does not exist in the file system.");
+        SG_LOG(SG_IO, SG_WARN, "ERROR: The path '" << path << "' does not exist in the file system.");
         return path;
     }
     std::string p(buf);