Skip to content
Open
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
29 changes: 29 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 Down Expand Up @@ -497,6 +498,34 @@ 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__)
const std::string command = "open \"" + filename + "\"";
if (std::system(command.c_str()) == 0)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

std::system() is not safe ; as a user could call this function with an input crafted to do malicious things...
So the solution would be to sanitize the inputs or the best solution is to use fork() and execvp() (for linux at least.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see, sorry I didn't know it was bad practice to use std::system. I'll make the changes for both macOS and linux.

success = true;
#else
const std::string command = "xdg-open \"" + filename + "\"";
if (std::system(command.c_str()) == 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