Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions Sofa/framework/Helper/src/sofa/helper/system/FileSystem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
# include <winerror.h>
# include <strsafe.h>
# include "Shlwapi.h" // for PathFileExists()
#include <shellapi.h>
#else
# include <dirent.h>
# include <sys/stat.h>
Expand All @@ -50,6 +51,15 @@
# include <unistd.h>
#endif

#if defined(__APPLE__)
#include <stdio.h>
#endif

#ifdef linux
#include <spawn.h>
#include <sys/wait.h>
#endif

#include <cassert>
#include <sofa/helper/system/SetDirectory.h>

Expand Down Expand Up @@ -497,6 +507,44 @@ std::string FileSystem::append(const std::string_view& existingPath, const std::
return std::string(existingPath) + "/" + std::string(toAppend);
}

bool FileSystem::openFileWithDefaultApplication(const std::string& filename)
{
bool success = false;

if (!filename.empty())
{
if (!FileSystem::exists(filename))
{
msg_error("FileSystem::openFileWithDefaultApplication()") << "File does not exist: " << filename;
return success;
}

#ifdef WIN32
if ((INT_PTR)ShellExecuteA(nullptr, "open", filename.c_str(), nullptr, nullptr, SW_SHOWNORMAL) > 32)
success = true;
#elif defined(__APPLE__)
pid_t pid; // points to a buffer that is used to return the process ID of the new child process.
char* argv[] = {const_cast<char*>("open"), vconst_cast<char*>(filename.c_str()), nullptr};
if (posix_spawn(&pid, "/usr/bin/open", nullptr, nullptr, argv, environ) == 0)
{
int status;
if (waitpid(pid, &status, 0) != -1 && WIFEXITED(status) && WEXITSTATUS(status) == 0)
success = true;
}
#else
pid_t pid; // points to a buffer that is used to return the process ID of the new child process.
const char* argv[] = {"xdg-open", filename.c_str(), nullptr};
if (posix_spawn(&pid, "/usr/bin/xdg-open", nullptr, nullptr, const_cast<char* const*>(argv), environ) == 0)
{
int status;
if (waitpid(pid, &status, 0) != -1 && WIFEXITED(status) && WEXITSTATUS(status) == 0)
success = true;
}
#endif
}

return success;
}

} // namespace system
} // namespace helper
Expand Down
3 changes: 3 additions & 0 deletions Sofa/framework/Helper/src/sofa/helper/system/FileSystem.h
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,9 @@ static std::string append(const std::string_view& existingPath, const std::strin
return append(append(existingPath, toAppend), args...);
}

/// Open a file with the default application associated to its type by the OS
static bool openFileWithDefaultApplication(const std::string& filename);

};


Expand Down
Loading