o removed waywars #endif
[asdcplib.git] / src / KM_fileio.cpp
index 27679318618e9204ebe3262e8077f66de1ce81bc..0dfa473dda79cbef35ee4557e7dae176a652342a 100644 (file)
@@ -48,6 +48,10 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 #include <mach-o/dyld.h>
 #endif
 
+#if defined(__OpenBSD__)
+#include <sys/sysctl.h>
+#endif
+
 using namespace Kumu;
 
 #ifdef KM_WIN32
@@ -75,6 +79,9 @@ struct iovec {
 typedef struct stat     fstat_t;
 #endif
 
+#if defined(__sun) && defined(__SVR4)
+#include <sys/statfs.h>
+#endif
 
 //
 static Kumu::Result_t
@@ -655,18 +662,29 @@ Kumu::GetExecutablePath(const std::string& default_path)
   size_t size = X_BUFSIZE;
   ssize_t rc = readlink("/proc/self/exe", path, size);
   success = ( rc != -1 );
-#elif defined(__OpenBSD__) || defined(__FreeBSD__)
-  size_t size = X_BUFSIZE;
-  ssize_t rc = readlink("/proc/curproc/file", path, size);
-  success = ( rc != -1 );
+#elif defined(__OpenBSD__)
+  // This fails if the CWD changes after the program has started but before the
+  // call to GetExecutablePath(). For least surprise, call GetExecutablePath()
+  // immediately in main() and save the value for later use.
+  const  char* p = getenv("_");
+  if ( p )
+    {
+      return Kumu::PathMakeAbsolute(p);
+    }
 #elif defined(__FreeBSD__)
+  // requires procfs
   size_t size = X_BUFSIZE;
   ssize_t rc = readlink("/proc/curproc/file", path, size);
   success = ( rc != -1 );
 #elif defined(__NetBSD__)
   size_t size = X_BUFSIZE;
-  ssize_t rc = readlink("/proc/curproc/file", path, size);
+  ssize_t rc = readlink("/proc/curproc/exe", path, size);
   success = ( rc != -1 );
+#elif defined(__sun) && defined(__SVR4)
+  size_t size = X_BUFSIZE;
+  char program[MAXPATHLEN];
+  snprintf(program, MAXPATHLEN, "/proc/%d/path/a.out", getpid());
+  ssize_t rc = readlink(program, path, size);
 #else
 #error GetExecutablePath --> Create a method for obtaining the executable name
 #endif
@@ -744,6 +762,53 @@ Kumu::FileWriter::Writev(const byte_t* buf, ui32_t buf_len)
 
 
 #ifdef KM_WIN32
+
+//
+Kumu::Result_t
+Kumu::wbstr_to_utf8(const Kumu::ByteString& in, std::string& out)
+{
+  out.erase();
+  assert(in.Length()%sizeof(wchar_t)==0);
+  const wchar_t* p = (const wchar_t*)in.RoData();
+
+  int stringLength = static_cast<int>( in.Length() );
+  int len = WideCharToMultiByte(CP_UTF8, 0, p, stringLength, NULL, 0, NULL, NULL);
+  char *mb_buf = new char[len];
+  WideCharToMultiByte(CP_UTF8, 0, p, stringLength, mb_buf, len, NULL, NULL);
+  out = mb_buf;
+  delete [] mb_buf;
+  return RESULT_OK;
+}
+
+//
+Kumu::Result_t
+Kumu::utf8_to_wbstr(const std::string& in, Kumu::ByteString& out)
+{
+  Result_t result = out.Capacity((in.size()+1)*sizeof(wchar_t));
+
+  if ( KM_FAILURE(result) )
+    {
+      return result;
+    }
+
+  assert(in.size()*sizeof(wchar_t)<=out.Capacity());
+  const char* read_pos = in.c_str();
+  wchar_t character, *write_pos = (wchar_t*)out.Data();
+
+  int stringLength = static_cast<int>( in.length() ) + 1;
+  int len = MultiByteToWideChar(CP_UTF8, 0, in.c_str(), stringLength, 0, 0);
+  result = out.Capacity(len*sizeof(wchar_t));
+  if ( KM_FAILURE(result) )
+    {
+      return result;
+    }
+  MultiByteToWideChar(CP_UTF8, 0, in.c_str(), stringLength, write_pos, len);
+  out.Length(len*sizeof(wchar_t));
+
+  return RESULT_OK;
+}
+
+
 //------------------------------------------------------------------------------------------
 //
 
@@ -751,11 +816,19 @@ Kumu::Result_t
 Kumu::FileReader::OpenRead(const std::string& filename) const
 {
   const_cast<FileReader*>(this)->m_Filename = filename;
-  
+  ByteString wb_filename;
+  Result_t result = utf8_to_wbstr(m_Filename, wb_filename);
+
+  if ( KM_FAILURE(result) )
+    {
+      return result;
+    }
+
   // suppress popup window on error
   UINT prev = ::SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX);
 
-  const_cast<FileReader*>(this)->m_Handle = ::CreateFileA(filename.c_str(),
+  const_cast<FileReader*>(this)->m_Handle =
+            ::CreateFileW((wchar_t*)wb_filename.RoData(),
                          (GENERIC_READ),                // open for reading
                          FILE_SHARE_READ,               // share for reading
                          NULL,                          // no security
@@ -870,16 +943,24 @@ Kumu::FileReader::Read(byte_t* buf, ui32_t buf_len, ui32_t* read_count) const
 //------------------------------------------------------------------------------------------
 //
 
+
 //
 Kumu::Result_t
 Kumu::FileWriter::OpenWrite(const std::string& filename)
 {
   m_Filename = filename;
-  
+  ByteString wb_filename;
+  Result_t result = utf8_to_wbstr(m_Filename, wb_filename);
+
+  if ( KM_FAILURE(result) )
+    {
+      return result;
+    }
+
   // suppress popup window on error
   UINT prev = ::SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX);
 
-  m_Handle = ::CreateFileA(filename.c_str(),
+  m_Handle = ::CreateFileW((wchar_t*)wb_filename.RoData(),
                          (GENERIC_WRITE|GENERIC_READ),  // open for reading
                          FILE_SHARE_READ,               // share for reading
                          NULL,                          // no security
@@ -1206,7 +1287,7 @@ Kumu::ReadFileIntoObject(const std::string& Filename, Kumu::IArchive& Object, ui
   if ( KM_SUCCESS(result) )
     {
       ui32_t read_count = 0;
-      FileWriter Reader;
+      FileReader Reader;
 
       result = Reader.OpenRead(Filename);
 
@@ -1266,7 +1347,7 @@ Kumu::ReadFileIntoBuffer(const std::string& Filename, Kumu::ByteString& Buffer,
   if ( KM_SUCCESS(result) )
     {
       ui32_t read_count = 0;
-      FileWriter Reader;
+      FileReader Reader;
 
       result = Reader.OpenRead(Filename);
 
@@ -1307,96 +1388,6 @@ Kumu::WriteBufferIntoFile(const Kumu::ByteString& Buffer, const std::string& Fil
 //
 
 
-// Win32 directory scanner
-//
-#ifdef KM_WIN32
-
-//
-Kumu::DirScanner::DirScanner(void) : m_Handle(-1) {}
-
-//
-//
-Result_t
-Kumu::DirScanner::Open(const std::string& filename)
-{
-  // we need to append a '*' to read the entire directory
-  ui32_t fn_len = filename.size(); 
-  char* tmp_file = (char*)malloc(fn_len + 8);
-
-  if ( tmp_file == 0 )
-    return RESULT_ALLOC;
-
-  strcpy(tmp_file, filename.c_str());
-  char* p = &tmp_file[fn_len] - 1;
-
-  if ( *p != '/' && *p != '\\' )
-    {
-      p++;
-      *p++ = '/';
-    }
-
-  *p++ = '*';
-  *p = 0;
-  // whew...
-
-  m_Handle = _findfirsti64(tmp_file, &m_FileInfo);
-  Result_t result = RESULT_OK;
-
-  if ( m_Handle == -1 )
-    result = RESULT_NOT_FOUND;
-
-  return result;
-}
-
-
-//
-//
-Result_t
-Kumu::DirScanner::Close()
-{
-  if ( m_Handle == -1 )
-    return RESULT_FILEOPEN;
-
-  if ( _findclose((long)m_Handle) == -1 )
-    return RESULT_FAIL;
-
-  m_Handle = -1;
-  return RESULT_OK;
-}
-
-
-// This sets filename param to the same per-instance buffer every time, so
-// the value will change on the next call
-Result_t
-Kumu::DirScanner::GetNext(char* filename)
-{
-  KM_TEST_NULL_L(filename);
-
-  if ( m_Handle == -1 )
-    return RESULT_FILEOPEN;
-
-  if ( m_FileInfo.name[0] == '\0' )
-    return RESULT_ENDOFFILE;
-
-  strncpy(filename, m_FileInfo.name, MaxFilePath);
-  Result_t result = RESULT_OK;
-
-  if ( _findnexti64((long)m_Handle, &m_FileInfo) == -1 )
-    {
-      m_FileInfo.name[0] = '\0';
-         
-      if ( errno != ENOENT )
-       result = RESULT_FAIL;
-    }
-
-  return result;
-}
-
-
-#else // KM_WIN32
-
-// POSIX directory scanner
-
 //
 Kumu::DirScanner::DirScanner(void) : m_Handle(NULL) {}
 
@@ -1550,6 +1541,9 @@ Kumu::DirScannerEx::GetNext(std::string& next_item_name, DirectoryEntryType_t& n
   if ( m_Handle == 0 )
     return RESULT_FILEOPEN;
 
+#if defined(__sun) && defined(__SVR4)
+  struct stat s;
+#endif
   struct dirent* entry;
 
   for (;;)
@@ -1562,6 +1556,28 @@ Kumu::DirScannerEx::GetNext(std::string& next_item_name, DirectoryEntryType_t& n
 
   next_item_name.assign(entry->d_name, strlen(entry->d_name));
 
+#if defined(__sun) && defined(__SVR4)
+
+  stat(entry->d_name, &s);
+
+  switch ( s.st_mode )
+    {
+    case S_IFDIR:
+      next_item_type = DET_DIR;
+      break;
+
+    case S_IFREG:
+      next_item_type = DET_FILE;
+      break;
+
+    case S_IFLNK:
+      next_item_type = DET_LINK;
+      break;
+
+    default:
+      next_item_type = DET_DEV;
+    }
+#else // __sun 
   switch ( entry->d_type )
     {
     case DT_DIR:
@@ -1579,14 +1595,11 @@ Kumu::DirScannerEx::GetNext(std::string& next_item_name, DirectoryEntryType_t& n
     default:
       next_item_type = DET_DEV;
     }
-
+#endif // __sun
   return RESULT_OK;
 }
 
 
-#endif // KM_WIN32
-
-
 //------------------------------------------------------------------------------------------
 
 //
@@ -1773,6 +1786,20 @@ Kumu::FreeSpaceForPath(const std::string& path, Kumu::fsize_t& free_space, Kumu:
 #else // KM_WIN32
   struct statfs s;
 
+#if defined(__sun) && defined(__SVR4)
+  if ( statfs(path.c_str(), &s, s.f_bsize, s.f_fstyp ) == 0 )
+    {      if ( s.f_blocks < 1 )
+       {
+         DefaultLogSink().Error("File system %s has impossible size: %ld\n",
+                                path.c_str(), s.f_blocks);
+         return RESULT_FAIL;
+       }
+
+      free_space = (Kumu::fsize_t)s.f_bsize * (Kumu::fsize_t)s.f_bfree;
+      total_space = (Kumu::fsize_t)s.f_bsize * (Kumu::fsize_t)s.f_blocks;
+      return RESULT_OK;
+    }
+#else
   if ( statfs(path.c_str(), &s) == 0 )
     {
       if ( s.f_blocks < 1 )
@@ -1796,6 +1823,7 @@ Kumu::FreeSpaceForPath(const std::string& path, Kumu::fsize_t& free_space, Kumu:
 
   DefaultLogSink().Error("FreeSpaceForPath statfs %s: %s\n", path.c_str(), strerror(errno));
   return RESULT_FAIL;
+#endif // __sun 
 #endif // KM_WIN32
 }