1
0
mirror of synced 2024-11-28 09:30:51 +01:00

sys: Refactor of filesystem functions. Fixed crashes where fs errors weren't caught correctly

Addresses the crash mentioned in #462
This commit is contained in:
WerWolv 2022-03-04 11:36:37 +01:00
parent 7866e3fc2a
commit 2739320f10
60 changed files with 442 additions and 398 deletions

View File

@ -113,7 +113,7 @@ set(LIBIMHEX_SOURCES
source/data_processor/node.cpp source/data_processor/node.cpp
source/helpers/utils.cpp source/helpers/utils.cpp
source/helpers/paths.cpp source/helpers/fs.cpp
source/helpers/magic.cpp source/helpers/magic.cpp
source/helpers/crypto.cpp source/helpers/crypto.cpp
source/helpers/net.cpp source/helpers/net.cpp
@ -149,7 +149,7 @@ if (APPLE)
endif () endif ()
endif () endif ()
set(LIBIMHEX_SOURCES ${LIBIMHEX_SOURCES} source/helpers/paths_mac.mm) set(LIBIMHEX_SOURCES ${LIBIMHEX_SOURCES} source/helpers/fs_macos.mm)
endif () endif ()
add_compile_definitions(IMHEX_PROJECT_NAME="${PROJECT_NAME}") add_compile_definitions(IMHEX_PROJECT_NAME="${PROJECT_NAME}")

View File

@ -2,7 +2,7 @@
#include <hex.hpp> #include <hex.hpp>
#include <hex/helpers/concepts.hpp> #include <hex/helpers/concepts.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <hex/pattern_language/token.hpp> #include <hex/pattern_language/token.hpp>
#include <hex/api/imhex_api.hpp> #include <hex/api/imhex_api.hpp>
@ -372,7 +372,7 @@ namespace hex {
namespace impl { namespace impl {
using Callback = std::function<bool(fs::path)>; using Callback = std::function<bool(std::fs::path)>;
struct Entry { struct Entry {
std::vector<std::string> extensions; std::vector<std::string> extensions;
Callback callback; Callback callback;

View File

@ -8,7 +8,7 @@
#include <functional> #include <functional>
#include <hex/api/imhex_api.hpp> #include <hex/api/imhex_api.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#define EVENT_DEF(event_name, ...) \ #define EVENT_DEF(event_name, ...) \
struct event_name final : public hex::Event<__VA_ARGS__> { \ struct event_name final : public hex::Event<__VA_ARGS__> { \
@ -101,7 +101,7 @@ namespace hex {
} }
/* Default Events */ /* Default Events */
EVENT_DEF(EventFileLoaded, fs::path); EVENT_DEF(EventFileLoaded, std::fs::path);
EVENT_DEF(EventFileUnloaded); EVENT_DEF(EventFileUnloaded);
EVENT_DEF(EventDataChanged); EVENT_DEF(EventDataChanged);
EVENT_DEF(EventHighlightingChanged); EVENT_DEF(EventHighlightingChanged);
@ -124,7 +124,7 @@ namespace hex {
EVENT_DEF(RequestSetPatternLanguageCode, std::string); EVENT_DEF(RequestSetPatternLanguageCode, std::string);
EVENT_DEF(RequestChangeWindowTitle, std::string); EVENT_DEF(RequestChangeWindowTitle, std::string);
EVENT_DEF(RequestCloseImHex, bool); EVENT_DEF(RequestCloseImHex, bool);
EVENT_DEF(RequestOpenFile, fs::path); EVENT_DEF(RequestOpenFile, std::fs::path);
EVENT_DEF(RequestChangeTheme, u32); EVENT_DEF(RequestChangeTheme, u32);
EVENT_DEF(RequestOpenPopup, std::string); EVENT_DEF(RequestOpenPopup, std::string);
EVENT_DEF(RequestCreateProvider, std::string, hex::prv::Provider **); EVENT_DEF(RequestCreateProvider, std::string, hex::prv::Provider **);

View File

@ -3,7 +3,7 @@
#include <hex.hpp> #include <hex.hpp>
#include <hex/helpers/fmt.hpp> #include <hex/helpers/fmt.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <string> #include <string>
@ -13,7 +13,7 @@ namespace hex {
class Plugin { class Plugin {
public: public:
explicit Plugin(const fs::path &path); explicit Plugin(const std::fs::path &path);
Plugin(const Plugin &) = delete; Plugin(const Plugin &) = delete;
Plugin(Plugin &&other) noexcept; Plugin(Plugin &&other) noexcept;
~Plugin(); ~Plugin();
@ -26,7 +26,7 @@ namespace hex {
void setImGuiContext(ImGuiContext *ctx) const; void setImGuiContext(ImGuiContext *ctx) const;
[[nodiscard]] bool isBuiltinPlugin() const; [[nodiscard]] bool isBuiltinPlugin() const;
[[nodiscard]] const fs::path &getPath() const; [[nodiscard]] const std::fs::path &getPath() const;
[[nodiscard]] bool isLoaded() const; [[nodiscard]] bool isLoaded() const;
@ -40,7 +40,7 @@ namespace hex {
using IsBuiltinPluginFunc = bool (*)(); using IsBuiltinPluginFunc = bool (*)();
void *m_handle = nullptr; void *m_handle = nullptr;
fs::path m_path; std::fs::path m_path;
mutable bool m_initialized = false; mutable bool m_initialized = false;
@ -65,7 +65,7 @@ namespace hex {
public: public:
PluginManager() = delete; PluginManager() = delete;
static bool load(const fs::path &pluginFolder); static bool load(const std::fs::path &pluginFolder);
static void unload(); static void unload();
static void reload(); static void reload();
@ -74,7 +74,7 @@ namespace hex {
} }
private: private:
static fs::path s_pluginFolder; static std::fs::path s_pluginFolder;
static std::vector<Plugin> s_plugins; static std::vector<Plugin> s_plugins;
}; };

View File

@ -6,18 +6,19 @@
#include <string_view> #include <string_view>
#include <vector> #include <vector>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
namespace hex { namespace hex {
class EncodingFile { class EncodingFile {
public: public:
enum class Type { enum class Type
{
Thingy Thingy
}; };
EncodingFile() = default; EncodingFile() = default;
EncodingFile(Type type, const fs::path &path); EncodingFile(Type type, const std::fs::path &path);
[[nodiscard]] std::pair<std::string_view, size_t> getEncodingFor(const std::vector<u8> &buffer) const; [[nodiscard]] std::pair<std::string_view, size_t> getEncodingFor(const std::vector<u8> &buffer) const;
[[nodiscard]] size_t getLongestSequence() const { return this->m_longestSequence; } [[nodiscard]] size_t getLongestSequence() const { return this->m_longestSequence; }

View File

@ -6,7 +6,7 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#if defined(OS_MACOS) #if defined(OS_MACOS)
#define off64_t off_t #define off64_t off_t
@ -16,7 +16,7 @@
#define ftruncate64 ftruncate #define ftruncate64 ftruncate
#endif #endif
namespace hex { namespace hex::fs {
class File { class File {
public: public:
@ -27,7 +27,7 @@ namespace hex {
Create Create
}; };
explicit File(const fs::path &path, Mode mode) noexcept; explicit File(const std::fs::path &path, Mode mode) noexcept;
File() noexcept; File() noexcept;
File(const File &) = delete; File(const File &) = delete;
File(File &&other) noexcept; File(File &&other) noexcept;
@ -38,7 +38,7 @@ namespace hex {
[[nodiscard]] bool isValid() const { [[nodiscard]] bool isValid() const {
return this->m_file != nullptr && fs::exists(this->m_path) && !fs::is_directory(this->m_path); return this->m_file != nullptr && fs::exists(this->m_path) && !fs::isDirectory(this->m_path);
} }
void seek(u64 offset); void seek(u64 offset);
@ -59,13 +59,13 @@ namespace hex {
bool remove(); bool remove();
auto getHandle() { return this->m_file; } auto getHandle() { return this->m_file; }
const fs::path &getPath() { return this->m_path; } const std::fs::path &getPath() { return this->m_path; }
void disableBuffering(); void disableBuffering();
private: private:
FILE *m_file; FILE *m_file;
fs::path m_path; std::fs::path m_path;
}; };
} }

View File

@ -0,0 +1,83 @@
#pragma once
#include <string>
#include <vector>
#include <filesystem>
#include <nfd.hpp>
namespace std::fs {
using namespace std::filesystem;
}
namespace hex::fs {
static inline bool exists(const std::fs::path &path) {
std::error_code error;
return std::filesystem::exists(path, error) && !error;
}
static inline bool createDirectories(const std::fs::path &path) {
std::error_code error;
return std::filesystem::create_directories(path, error) && !error;
}
static inline bool isRegularFile(const std::fs::path &path) {
std::error_code error;
return std::filesystem::is_regular_file(path, error) && !error;
}
static inline bool copyFile(const std::fs::path &from, const std::fs::path &to, std::fs::copy_options = std::fs::copy_options::none) {
std::error_code error;
return std::filesystem::copy_file(from, to, error) && !error;
}
static inline bool isDirectory(const std::fs::path &path) {
std::error_code error;
return std::filesystem::is_directory(path, error) && !error;
}
static inline bool remove(const std::fs::path &path) {
std::error_code error;
return std::filesystem::remove(path, error) && !error;
}
static inline uintmax_t getFileSize(const std::fs::path &path) {
std::error_code error;
auto size = std::filesystem::file_size(path, error);
if (error) return 0;
else return size;
}
bool isPathWritable(std::fs::path path);
enum class DialogMode
{
Open,
Save,
Folder
};
bool openFileBrowser(const std::string &title, DialogMode mode, const std::vector<nfdfilteritem_t> &validExtensions, const std::function<void(std::fs::path)> &callback, const std::string &defaultPath = {});
enum class ImHexPath
{
Patterns,
PatternsInclude,
Magic,
Python,
Plugins,
Yara,
Config,
Resources,
Constants,
Encodings,
Logs
};
std::string getExecutablePath();
std::vector<std::fs::path> getDefaultPaths(ImHexPath path, bool listNonExisting = false);
}

View File

@ -3,7 +3,7 @@
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
struct _object; struct _object;
typedef struct _object PyObject; typedef struct _object PyObject;
@ -18,13 +18,13 @@ namespace hex {
public: public:
LoaderScript() = delete; LoaderScript() = delete;
static bool processFile(const fs::path &scriptPath); static bool processFile(const std::fs::path &scriptPath);
static void setFilePath(const fs::path &filePath) { LoaderScript::s_filePath = filePath; } static void setFilePath(const std::fs::path &filePath) { LoaderScript::s_filePath = filePath; }
static void setDataProvider(prv::Provider *provider) { LoaderScript::s_dataProvider = provider; } static void setDataProvider(prv::Provider *provider) { LoaderScript::s_dataProvider = provider; }
private: private:
static inline fs::path s_filePath; static inline std::fs::path s_filePath;
static inline prv::Provider *s_dataProvider; static inline prv::Provider *s_dataProvider;
static PyObject *Py_getFilePath(PyObject *self, PyObject *args); static PyObject *Py_getFilePath(PyObject *self, PyObject *args);

View File

@ -12,7 +12,7 @@
#include <nlohmann/json_fwd.hpp> #include <nlohmann/json_fwd.hpp>
#include <curl/system.h> #include <curl/system.h>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
using CURL = void; using CURL = void;
struct curl_slist; struct curl_slist;
@ -40,8 +40,8 @@ namespace hex {
std::future<Response<std::string>> getString(const std::string &url, u32 timeout = DefaultTimeout); std::future<Response<std::string>> getString(const std::string &url, u32 timeout = DefaultTimeout);
std::future<Response<nlohmann::json>> getJson(const std::string &url, u32 timeout = DefaultTimeout); std::future<Response<nlohmann::json>> getJson(const std::string &url, u32 timeout = DefaultTimeout);
std::future<Response<std::string>> uploadFile(const std::string &url, const fs::path &filePath, u32 timeout = DefaultTimeout); std::future<Response<std::string>> uploadFile(const std::string &url, const std::fs::path &filePath, u32 timeout = DefaultTimeout);
std::future<Response<void>> downloadFile(const std::string &url, const fs::path &filePath, u32 timeout = DefaultTimeout); std::future<Response<void>> downloadFile(const std::string &url, const std::fs::path &filePath, u32 timeout = DefaultTimeout);
[[nodiscard]] std::string encode(const std::string &input); [[nodiscard]] std::string encode(const std::string &input);

View File

@ -1,29 +0,0 @@
#pragma once
#include <string>
#include <vector>
#include <filesystem>
namespace hex {
namespace fs = std::filesystem;
enum class ImHexPath {
Patterns,
PatternsInclude,
Magic,
Python,
Plugins,
Yara,
Config,
Resources,
Constants,
Encodings,
Logs
};
std::string getExecutablePath();
std::vector<fs::path> getPath(ImHexPath path, bool listNonExisting = false);
}

View File

@ -8,7 +8,7 @@
#include <hex/api/imhex_api.hpp> #include <hex/api/imhex_api.hpp>
#include <hex/api/event.hpp> #include <hex/api/event.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
namespace hex { namespace hex {
@ -16,8 +16,8 @@ namespace hex {
public: public:
ProjectFile() = delete; ProjectFile() = delete;
static bool load(const fs::path &filePath); static bool load(const std::fs::path &filePath);
static bool store(fs::path filePath = {}); static bool store(std::fs::path filePath = {});
[[nodiscard]] static bool hasUnsavedChanges() { [[nodiscard]] static bool hasUnsavedChanges() {
return ProjectFile::s_hasUnsavedChanged; return ProjectFile::s_hasUnsavedChanged;
@ -29,10 +29,10 @@ namespace hex {
ProjectFile::s_hasUnsavedChanged = true; ProjectFile::s_hasUnsavedChanged = true;
if (setWindowTitle) if (setWindowTitle)
EventManager::post<RequestChangeWindowTitle>(fs::path(getFilePath()).filename().string()); EventManager::post<RequestChangeWindowTitle>(std::fs::path(getFilePath()).filename().string());
} }
[[nodiscard]] static const fs::path &getProjectFilePath() { [[nodiscard]] static const std::fs::path &getProjectFilePath() {
return ProjectFile::s_currProjectFilePath; return ProjectFile::s_currProjectFilePath;
} }
@ -41,11 +41,11 @@ namespace hex {
} }
[[nodiscard]] static const fs::path &getFilePath() { [[nodiscard]] static const std::fs::path &getFilePath() {
return ProjectFile::s_filePath; return ProjectFile::s_filePath;
} }
static void setFilePath(const fs::path &filePath) { static void setFilePath(const std::fs::path &filePath) {
ProjectFile::s_filePath = filePath; ProjectFile::s_filePath = filePath;
EventManager::post<RequestChangeWindowTitle>(filePath.filename().string()); EventManager::post<RequestChangeWindowTitle>(filePath.filename().string());
@ -92,10 +92,10 @@ namespace hex {
} }
private: private:
static fs::path s_currProjectFilePath; static std::fs::path s_currProjectFilePath;
static bool s_hasUnsavedChanged; static bool s_hasUnsavedChanged;
static fs::path s_filePath; static std::fs::path s_filePath;
static std::string s_pattern; static std::string s_pattern;
static Patches s_patches; static Patches s_patches;
static std::list<ImHexApi::Bookmarks::Entry> s_bookmarks; static std::list<ImHexApi::Bookmarks::Entry> s_bookmarks;

View File

@ -3,7 +3,7 @@
#include <hex.hpp> #include <hex.hpp>
#include <hex/helpers/concepts.hpp> #include <hex/helpers/concepts.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <array> #include <array>
#include <bit> #include <bit>
@ -18,8 +18,6 @@
#include <variant> #include <variant>
#include <vector> #include <vector>
#include <nfd.hpp>
#define TOKEN_CONCAT_IMPL(x, y) x##y #define TOKEN_CONCAT_IMPL(x, y) x##y
#define TOKEN_CONCAT(x, y) TOKEN_CONCAT_IMPL(x, y) #define TOKEN_CONCAT(x, y) TOKEN_CONCAT_IMPL(x, y)
#define ANONYMOUS_VARIABLE(prefix) TOKEN_CONCAT(prefix, __COUNTER__) #define ANONYMOUS_VARIABLE(prefix) TOKEN_CONCAT(prefix, __COUNTER__)
@ -44,8 +42,6 @@ namespace hex {
std::string encodeByteString(const std::vector<u8> &bytes); std::string encodeByteString(const std::vector<u8> &bytes);
std::vector<u8> decodeByteString(const std::string &string); std::vector<u8> decodeByteString(const std::string &string);
bool isPathWritable(fs::path path);
[[nodiscard]] constexpr inline u64 extract(u8 from, u8 to, const hex::unsigned_integral auto &value) { [[nodiscard]] constexpr inline u64 extract(u8 from, u8 to, const hex::unsigned_integral auto &value) {
if (from < to) std::swap(from, to); if (from < to) std::swap(from, to);
@ -268,15 +264,6 @@ namespace hex {
trimRight(s); trimRight(s);
} }
enum class DialogMode
{
Open,
Save,
Folder
};
bool openFileBrowser(const std::string &title, DialogMode mode, const std::vector<nfdfilteritem_t> &validExtensions, const std::function<void(fs::path)> &callback, const std::string &defaultPath = {});
float float16ToFloat32(u16 float16); float float16ToFloat32(u16 float16);
inline bool equalsIgnoreCase(const std::string &left, const std::string &right) { inline bool equalsIgnoreCase(const std::string &left, const std::string &right) {

View File

@ -35,7 +35,7 @@ namespace hex::pl {
[[nodiscard]] std::optional<std::vector<std::shared_ptr<ASTNode>>> parseString(const std::string &code); [[nodiscard]] std::optional<std::vector<std::shared_ptr<ASTNode>>> parseString(const std::string &code);
[[nodiscard]] bool executeString(prv::Provider *provider, const std::string &string, const std::map<std::string, Token::Literal> &envVars = {}, const std::map<std::string, Token::Literal> &inVariables = {}, bool checkResult = true); [[nodiscard]] bool executeString(prv::Provider *provider, const std::string &string, const std::map<std::string, Token::Literal> &envVars = {}, const std::map<std::string, Token::Literal> &inVariables = {}, bool checkResult = true);
[[nodiscard]] bool executeFile(prv::Provider *provider, const fs::path &path, const std::map<std::string, Token::Literal> &envVars = {}, const std::map<std::string, Token::Literal> &inVariables = {}); [[nodiscard]] bool executeFile(prv::Provider *provider, const std::fs::path &path, const std::map<std::string, Token::Literal> &envVars = {}, const std::map<std::string, Token::Literal> &inVariables = {});
[[nodiscard]] std::pair<bool, std::optional<Token::Literal>> executeFunction(prv::Provider *provider, const std::string &code); [[nodiscard]] std::pair<bool, std::optional<Token::Literal>> executeFunction(prv::Provider *provider, const std::string &code);
[[nodiscard]] const std::vector<std::shared_ptr<ASTNode>> &getCurrentAST() const; [[nodiscard]] const std::vector<std::shared_ptr<ASTNode>> &getCurrentAST() const;

View File

@ -9,7 +9,7 @@
#include <unordered_map> #include <unordered_map>
#include <utility> #include <utility>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <hex/pattern_language/error.hpp> #include <hex/pattern_language/error.hpp>
@ -41,7 +41,7 @@ namespace hex::pl {
std::set<std::tuple<std::string, std::string, u32>> m_defines; std::set<std::tuple<std::string, std::string, u32>> m_defines;
std::set<std::tuple<std::string, std::string, u32>> m_pragmas; std::set<std::tuple<std::string, std::string, u32>> m_pragmas;
std::set<fs::path> m_onceIncludedFiles; std::set<std::fs::path> m_onceIncludedFiles;
std::optional<PatternLanguageError> m_error; std::optional<PatternLanguageError> m_error;

View File

@ -9,7 +9,7 @@
#include <vector> #include <vector>
#include <hex/providers/overlay.hpp> #include <hex/providers/overlay.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
namespace hex::pl { namespace hex::pl {
class PatternLanguage; class PatternLanguage;
@ -37,7 +37,7 @@ namespace hex::prv {
virtual void insert(u64 offset, size_t size); virtual void insert(u64 offset, size_t size);
virtual void save(); virtual void save();
virtual void saveAs(const fs::path &path); virtual void saveAs(const std::fs::path &path);
virtual void readRaw(u64 offset, void *buffer, size_t size) = 0; virtual void readRaw(u64 offset, void *buffer, size_t size) = 0;
virtual void writeRaw(u64 offset, const void *buffer, size_t size) = 0; virtual void writeRaw(u64 offset, const void *buffer, size_t size) = 0;

View File

@ -41,7 +41,7 @@ namespace hex {
static void showFatalPopup(const std::string &errorMessage); static void showFatalPopup(const std::string &errorMessage);
static void showYesNoQuestionPopup(const std::string &message, const std::function<void()> &yesCallback, const std::function<void()> &noCallback); static void showYesNoQuestionPopup(const std::string &message, const std::function<void()> &yesCallback, const std::function<void()> &noCallback);
static void showFileChooserPopup(const std::vector<fs::path> &paths, const std::vector<nfdfilteritem_t> &validExtensions, const std::function<void(fs::path)> &callback); static void showFileChooserPopup(const std::vector<std::fs::path> &paths, const std::vector<nfdfilteritem_t> &validExtensions, const std::function<void(std::fs::path)> &callback);
[[nodiscard]] virtual bool hasViewMenuItemEntry() const; [[nodiscard]] virtual bool hasViewMenuItemEntry() const;
[[nodiscard]] virtual ImVec2 getMinSize() const; [[nodiscard]] virtual ImVec2 getMinSize() const;
@ -76,8 +76,8 @@ namespace hex {
static std::function<void()> s_yesCallback, s_noCallback; static std::function<void()> s_yesCallback, s_noCallback;
static u32 s_selectableFileIndex; static u32 s_selectableFileIndex;
static std::vector<fs::path> s_selectableFiles; static std::vector<std::fs::path> s_selectableFiles;
static std::function<void(fs::path)> s_selectableFileOpenCallback; static std::function<void(std::fs::path)> s_selectableFileOpenCallback;
static std::vector<nfdfilteritem_t> s_selectableFilesValidExtensions; static std::vector<nfdfilteritem_t> s_selectableFilesValidExtensions;
static ImFontAtlas *s_fontAtlas; static ImFontAtlas *s_fontAtlas;

View File

@ -1,6 +1,6 @@
#include <hex/api/content_registry.hpp> #include <hex/api/content_registry.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <hex/helpers/logger.hpp> #include <hex/helpers/logger.hpp>
#include <hex/ui/view.hpp> #include <hex/ui/view.hpp>
@ -16,7 +16,7 @@ namespace hex {
void load() { void load() {
bool loaded = false; bool loaded = false;
for (const auto &dir : hex::getPath(ImHexPath::Config)) { for (const auto &dir : fs::getDefaultPaths(fs::ImHexPath::Config)) {
std::ifstream settingsFile(dir / "settings.json"); std::ifstream settingsFile(dir / "settings.json");
if (settingsFile.good()) { if (settingsFile.good()) {
@ -31,7 +31,7 @@ namespace hex {
} }
void store() { void store() {
for (const auto &dir : hex::getPath(ImHexPath::Config)) { for (const auto &dir : fs::getDefaultPaths(fs::ImHexPath::Config)) {
std::ofstream settingsFile(dir / "settings.json", std::ios::trunc); std::ofstream settingsFile(dir / "settings.json", std::ios::trunc);
if (settingsFile.good()) { if (settingsFile.good()) {

View File

@ -7,7 +7,7 @@
namespace hex { namespace hex {
Plugin::Plugin(const fs::path &path) : m_path(path) { Plugin::Plugin(const std::fs::path &path) : m_path(path) {
this->m_handle = dlopen(path.string().c_str(), RTLD_LAZY); this->m_handle = dlopen(path.string().c_str(), RTLD_LAZY);
if (this->m_handle == nullptr) { if (this->m_handle == nullptr) {
@ -15,7 +15,7 @@ namespace hex {
return; return;
} }
auto pluginName = fs::path(path).stem().string(); auto pluginName = std::fs::path(path).stem().string();
this->m_initializePluginFunction = getPluginFunction<InitializePluginFunc>("initializePlugin"); this->m_initializePluginFunction = getPluginFunction<InitializePluginFunc>("initializePlugin");
this->m_getPluginNameFunction = getPluginFunction<GetPluginNameFunc>("getPluginName"); this->m_getPluginNameFunction = getPluginFunction<GetPluginNameFunc>("getPluginName");
@ -110,7 +110,7 @@ namespace hex {
return false; return false;
} }
const fs::path &Plugin::getPath() const { const std::fs::path &Plugin::getPath() const {
return this->m_path; return this->m_path;
} }
@ -124,16 +124,16 @@ namespace hex {
} }
fs::path PluginManager::s_pluginFolder; std::fs::path PluginManager::s_pluginFolder;
std::vector<Plugin> PluginManager::s_plugins; std::vector<Plugin> PluginManager::s_plugins;
bool PluginManager::load(const fs::path &pluginFolder) { bool PluginManager::load(const std::fs::path &pluginFolder) {
if (!fs::exists(pluginFolder)) if (!fs::exists(pluginFolder))
return false; return false;
PluginManager::s_pluginFolder = pluginFolder; PluginManager::s_pluginFolder = pluginFolder;
for (auto &pluginPath : fs::directory_iterator(pluginFolder)) { for (auto &pluginPath : std::fs::directory_iterator(pluginFolder)) {
if (pluginPath.is_regular_file() && pluginPath.path().extension() == ".hexplug") if (pluginPath.is_regular_file() && pluginPath.path().extension() == ".hexplug")
PluginManager::s_plugins.emplace_back(pluginPath.path().string()); PluginManager::s_plugins.emplace_back(pluginPath.path().string());
} }

View File

@ -6,7 +6,7 @@
namespace hex { namespace hex {
EncodingFile::EncodingFile(Type type, const fs::path &path) { EncodingFile::EncodingFile(Type type, const std::fs::path &path) {
std::ifstream encodingFile(path.c_str()); std::ifstream encodingFile(path.c_str());
switch (type) { switch (type) {

View File

@ -1,9 +1,9 @@
#include <hex/helpers/file.hpp> #include <hex/helpers/file.hpp>
#include <unistd.h> #include <unistd.h>
namespace hex { namespace hex::fs {
File::File(const fs::path &path, Mode mode) noexcept : m_path(path) { File::File(const std::fs::path &path, Mode mode) noexcept : m_path(path) {
if (mode == File::Mode::Read) if (mode == File::Mode::Read)
this->m_file = fopen64(path.string().c_str(), "rb"); this->m_file = fopen64(path.string().c_str(), "rb");
else if (mode == File::Mode::Write) else if (mode == File::Mode::Write)

View File

@ -1,5 +1,6 @@
#include <hex/api/content_registry.hpp> #include <hex/api/content_registry.hpp>
#include <hex/helpers/paths_mac.h> #include <hex/helpers/fs_macos.h>
#include <hex/helpers/file.hpp>
#include <xdg.hpp> #include <xdg.hpp>
@ -14,7 +15,7 @@
#include <algorithm> #include <algorithm>
#include <filesystem> #include <filesystem>
namespace hex { namespace hex::fs {
std::string getExecutablePath() { std::string getExecutablePath() {
#if defined(OS_WINDOWS) #if defined(OS_WINDOWS)
@ -34,8 +35,57 @@ namespace hex {
#endif #endif
} }
std::vector<fs::path> getPath(ImHexPath path, bool listNonExisting) {
std::vector<fs::path> result; bool isPathWritable(std::fs::path path) {
constexpr static auto TestFileName = "__imhex__tmp__";
{
File file(path / TestFileName, File::Mode::Read);
if (file.isValid()) {
if (!file.remove())
return false;
}
}
File file(path / TestFileName, File::Mode::Create);
bool result = file.isValid();
if (!file.remove())
return false;
return result;
}
bool openFileBrowser(const std::string &title, DialogMode mode, const std::vector<nfdfilteritem_t> &validExtensions, const std::function<void(std::fs::path)> &callback, const std::string &defaultPath) {
NFD::Init();
nfdchar_t *outPath;
nfdresult_t result;
switch (mode) {
case DialogMode::Open:
result = NFD::OpenDialog(outPath, validExtensions.data(), validExtensions.size(), defaultPath.c_str());
break;
case DialogMode::Save:
result = NFD::SaveDialog(outPath, validExtensions.data(), validExtensions.size(), defaultPath.c_str());
break;
case DialogMode::Folder:
result = NFD::PickFolder(outPath, defaultPath.c_str());
break;
default:
__builtin_unreachable();
}
if (result == NFD_OKAY) {
callback(reinterpret_cast<const char8_t *>(outPath));
NFD::FreePath(outPath);
}
NFD::Quit();
return result == NFD_OKAY;
}
std::vector<std::fs::path> getDefaultPaths(ImHexPath path, bool listNonExisting) {
std::vector<std::fs::path> result;
const auto exePath = getExecutablePath(); const auto exePath = getExecutablePath();
const std::string settingName { "hex.builtin.setting.folders" }; const std::string settingName { "hex.builtin.setting.folders" };
auto userDirs = ContentRegistry::Settings::read(settingName, settingName, std::vector<std::string> {}); auto userDirs = ContentRegistry::Settings::read(settingName, settingName, std::vector<std::string> {});
@ -47,9 +97,9 @@ namespace hex {
}; };
#if defined(OS_WINDOWS) #if defined(OS_WINDOWS)
const auto parentDir = fs::path(exePath).parent_path(); const auto parentDir = std::fs::path(exePath).parent_path();
fs::path appDataDir; std::fs::path appDataDir;
{ {
LPWSTR wAppDataPath = nullptr; LPWSTR wAppDataPath = nullptr;
if (!SUCCEEDED(SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_CREATE, nullptr, &wAppDataPath))) if (!SUCCEEDED(SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_CREATE, nullptr, &wAppDataPath)))
@ -59,7 +109,7 @@ namespace hex {
CoTaskMemFree(wAppDataPath); CoTaskMemFree(wAppDataPath);
} }
std::vector<fs::path> paths = { appDataDir / "imhex", parentDir }; std::vector<std::fs::path> paths = { appDataDir / "imhex", parentDir };
switch (path) { switch (path) {
case ImHexPath::Patterns: case ImHexPath::Patterns:
@ -126,9 +176,9 @@ namespace hex {
} }
#elif defined(OS_MACOS) #elif defined(OS_MACOS)
// Get path to special directories // Get path to special directories
const fs::path applicationSupportDir(getMacApplicationSupportDirectoryPath()); const std::fs::path applicationSupportDir(getMacApplicationSupportDirectoryPath());
std::vector<fs::path> paths = { applicationSupportDir, exePath }; std::vector<std::fs::path> paths = { applicationSupportDir, exePath };
switch (path) { switch (path) {
case ImHexPath::Patterns: case ImHexPath::Patterns:
@ -170,8 +220,8 @@ namespace hex {
__builtin_unreachable(); __builtin_unreachable();
} }
#else #else
std::vector<fs::path> configDirs = xdg::ConfigDirs(); std::vector<std::fs::path> configDirs = xdg::ConfigDirs();
std::vector<fs::path> dataDirs = xdg::DataDirs(); std::vector<std::fs::path> dataDirs = xdg::DataDirs();
configDirs.push_back(xdg::ConfigHomeDir()); configDirs.push_back(xdg::ConfigHomeDir());
dataDirs.push_back(xdg::DataHomeDir()); dataDirs.push_back(xdg::DataHomeDir());
@ -231,7 +281,7 @@ namespace hex {
if (!listNonExisting) { if (!listNonExisting) {
result.erase(std::remove_if(result.begin(), result.end(), [](const auto &path) { result.erase(std::remove_if(result.begin(), result.end(), [](const auto &path) {
return !fs::is_directory(path); return !fs::isDirectory(path);
}), }),
result.end()); result.end());
} }

View File

@ -1,7 +1,7 @@
#include <hex/helpers/loader_script_handler.hpp> #include <hex/helpers/loader_script_handler.hpp>
#include <hex/helpers/utils.hpp> #include <hex/helpers/utils.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <hex/helpers/file.hpp> #include <hex/helpers/file.hpp>
#include <hex/ui/view.hpp> #include <hex/ui/view.hpp>
#include <hex/providers/provider.hpp> #include <hex/providers/provider.hpp>
@ -178,11 +178,11 @@ namespace hex {
return createStructureType("union", args); return createStructureType("union", args);
} }
bool LoaderScript::processFile(const fs::path &scriptPath) { bool LoaderScript::processFile(const std::fs::path &scriptPath) {
Py_SetProgramName(Py_DecodeLocale("ImHex", nullptr)); Py_SetProgramName(Py_DecodeLocale("ImHex", nullptr));
for (const auto &dir : hex::getPath(ImHexPath::Python)) { for (const auto &dir : fs::getDefaultPaths(fs::ImHexPath::Python)) {
if (fs::exists(fs::path(dir / "lib" / "python" PYTHON_VERSION_MAJOR_MINOR))) { if (fs::exists(std::fs::path(dir / "lib" / "python" PYTHON_VERSION_MAJOR_MINOR))) {
Py_SetPythonHome(Py_DecodeLocale(dir.string().c_str(), nullptr)); Py_SetPythonHome(Py_DecodeLocale(dir.string().c_str(), nullptr));
break; break;
} }
@ -218,7 +218,7 @@ namespace hex {
PyList_Insert(sysPath, 0, path); PyList_Insert(sysPath, 0, path);
} }
File scriptFile(scriptPath, File::Mode::Read); fs::File scriptFile(scriptPath, fs::File::Mode::Read);
PyRun_SimpleFile(scriptFile.getHandle(), scriptFile.getPath().string().c_str()); PyRun_SimpleFile(scriptFile.getHandle(), scriptFile.getPath().string().c_str());
Py_Finalize(); Py_Finalize();

View File

@ -1,13 +1,13 @@
#include <hex/helpers/logger.hpp> #include <hex/helpers/logger.hpp>
#include <hex/helpers/file.hpp> #include <hex/helpers/file.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <hex/helpers/fmt.hpp> #include <hex/helpers/fmt.hpp>
#include <iostream> #include <iostream>
namespace hex::log { namespace hex::log {
static File g_loggerFile; static fs::File g_loggerFile;
FILE *getDestination() { FILE *getDestination() {
if (g_loggerFile.isValid()) if (g_loggerFile.isValid())
@ -23,9 +23,9 @@ namespace hex::log {
void redirectToFile() { void redirectToFile() {
if (g_loggerFile.isValid()) return; if (g_loggerFile.isValid()) return;
for (const auto &path : hex::getPath(ImHexPath::Logs, true)) { for (const auto &path : fs::getDefaultPaths(fs::ImHexPath::Logs, true)) {
fs::create_directories(path); fs::createDirectories(path);
g_loggerFile = File(path / hex::format("{0:%Y%m%d_%H%M%S}.log", fmt::localtime(std::chrono::system_clock::now())), File::Mode::Create); g_loggerFile = fs::File(path / hex::format("{0:%Y%m%d_%H%M%S}.log", fmt::localtime(std::chrono::system_clock::now())), fs::File::Mode::Create);
g_loggerFile.disableBuffering(); g_loggerFile.disableBuffering();
if (g_loggerFile.isValid()) break; if (g_loggerFile.isValid()) break;

View File

@ -1,7 +1,7 @@
#include <hex/helpers/magic.hpp> #include <hex/helpers/magic.hpp>
#include <hex/helpers/utils.hpp> #include <hex/helpers/utils.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <hex/providers/provider.hpp> #include <hex/providers/provider.hpp>
@ -24,8 +24,8 @@ namespace hex::magic {
std::string magicFiles; std::string magicFiles;
std::error_code error; std::error_code error;
for (const auto &dir : hex::getPath(ImHexPath::Magic)) { for (const auto &dir : fs::getDefaultPaths(fs::ImHexPath::Magic)) {
for (const auto &entry : fs::directory_iterator(dir, error)) { for (const auto &entry : std::fs::directory_iterator(dir, error)) {
if (entry.is_regular_file() && ((sourceFiles && entry.path().extension().empty()) || (!sourceFiles && entry.path().extension() == ".mgc"))) if (entry.is_regular_file() && ((sourceFiles && entry.path().extension().empty()) || (!sourceFiles && entry.path().extension() == ".mgc")))
magicFiles += entry.path().string() + MAGIC_PATH_SEPARATOR; magicFiles += entry.path().string() + MAGIC_PATH_SEPARATOR;
} }

View File

@ -171,7 +171,7 @@ namespace hex {
}); });
} }
std::future<Response<std::string>> Net::uploadFile(const std::string &url, const fs::path &filePath, u32 timeout) { std::future<Response<std::string>> Net::uploadFile(const std::string &url, const std::fs::path &filePath, u32 timeout) {
this->m_transmissionActive.lock(); this->m_transmissionActive.lock();
return std::async(std::launch::async, [=, this] { return std::async(std::launch::async, [=, this] {
@ -179,7 +179,7 @@ namespace hex {
ON_SCOPE_EXIT { this->m_transmissionActive.unlock(); }; ON_SCOPE_EXIT { this->m_transmissionActive.unlock(); };
File file(filePath.string(), File::Mode::Read); fs::File file(filePath.string(), fs::File::Mode::Read);
if (!file.isValid()) if (!file.isValid())
return Response<std::string> { 400, {} }; return Response<std::string> { 400, {} };
@ -209,7 +209,7 @@ namespace hex {
}); });
} }
std::future<Response<void>> Net::downloadFile(const std::string &url, const fs::path &filePath, u32 timeout) { std::future<Response<void>> Net::downloadFile(const std::string &url, const std::fs::path &filePath, u32 timeout) {
this->m_transmissionActive.lock(); this->m_transmissionActive.lock();
return std::async(std::launch::async, [=, this] { return std::async(std::launch::async, [=, this] {
@ -217,7 +217,7 @@ namespace hex {
ON_SCOPE_EXIT { this->m_transmissionActive.unlock(); }; ON_SCOPE_EXIT { this->m_transmissionActive.unlock(); };
File file(filePath.string(), File::Mode::Create); fs::File file(filePath.string(), fs::File::Mode::Create);
if (!file.isValid()) if (!file.isValid())
return Response<void> { 400 }; return Response<void> { 400 };

View File

@ -9,10 +9,10 @@ using json = nlohmann::json;
namespace hex { namespace hex {
fs::path ProjectFile::s_currProjectFilePath; std::fs::path ProjectFile::s_currProjectFilePath;
bool ProjectFile::s_hasUnsavedChanged = false; bool ProjectFile::s_hasUnsavedChanged = false;
fs::path ProjectFile::s_filePath; std::fs::path ProjectFile::s_filePath;
std::string ProjectFile::s_pattern; std::string ProjectFile::s_pattern;
Patches ProjectFile::s_patches; Patches ProjectFile::s_patches;
std::list<ImHexApi::Bookmarks::Entry> ProjectFile::s_bookmarks; std::list<ImHexApi::Bookmarks::Entry> ProjectFile::s_bookmarks;
@ -46,7 +46,7 @@ namespace hex {
} }
bool ProjectFile::load(const fs::path &filePath) { bool ProjectFile::load(const std::fs::path &filePath) {
ProjectFile::s_hasUnsavedChanged = false; ProjectFile::s_hasUnsavedChanged = false;
json projectFileData; json projectFileData;
@ -55,7 +55,7 @@ namespace hex {
std::ifstream projectFile(filePath.c_str()); std::ifstream projectFile(filePath.c_str());
projectFile >> projectFileData; projectFile >> projectFileData;
ProjectFile::s_filePath = fs::path(projectFileData["filePath"].get<std::string>()); ProjectFile::s_filePath = std::fs::path(projectFileData["filePath"].get<std::string>());
ProjectFile::s_pattern = projectFileData["pattern"]; ProjectFile::s_pattern = projectFileData["pattern"];
ProjectFile::s_patches = projectFileData["patches"].get<Patches>(); ProjectFile::s_patches = projectFileData["patches"].get<Patches>();
ProjectFile::s_dataProcessorContent = projectFileData["dataProcessor"]; ProjectFile::s_dataProcessorContent = projectFileData["dataProcessor"];
@ -80,7 +80,7 @@ namespace hex {
return true; return true;
} }
bool ProjectFile::store(fs::path filePath) { bool ProjectFile::store(std::fs::path filePath) {
EventManager::post<EventProjectFileStore>(); EventManager::post<EventProjectFileStore>();
json projectFileData; json projectFileData;

View File

@ -394,53 +394,6 @@ namespace hex {
return result; return result;
} }
bool isPathWritable(fs::path path) {
constexpr static auto TestFileName = "__imhex__tmp__";
{
File file(path / TestFileName, File::Mode::Read);
if (file.isValid()) {
if (!file.remove())
return false;
}
}
File file(path / TestFileName, File::Mode::Create);
bool result = file.isValid();
if (!file.remove())
return false;
return result;
}
bool openFileBrowser(const std::string &title, DialogMode mode, const std::vector<nfdfilteritem_t> &validExtensions, const std::function<void(fs::path)> &callback, const std::string &defaultPath) {
NFD::Init();
nfdchar_t *outPath;
nfdresult_t result;
switch (mode) {
case DialogMode::Open:
result = NFD::OpenDialog(outPath, validExtensions.data(), validExtensions.size(), defaultPath.c_str());
break;
case DialogMode::Save:
result = NFD::SaveDialog(outPath, validExtensions.data(), validExtensions.size(), defaultPath.c_str());
break;
case DialogMode::Folder:
result = NFD::PickFolder(outPath, defaultPath.c_str());
break;
default:
__builtin_unreachable();
}
if (result == NFD_OKAY) {
callback(reinterpret_cast<const char8_t *>(outPath));
NFD::FreePath(outPath);
}
NFD::Quit();
return result == NFD_OKAY;
}
float float16ToFloat32(u16 float16) { float float16ToFloat32(u16 float16) {
u32 sign = float16 >> 15; u32 sign = float16 >> 15;
u32 exponent = (float16 >> 10) & 0x1F; u32 exponent = (float16 >> 10) & 0x1F;

View File

@ -184,8 +184,8 @@ namespace hex::pl {
return true; return true;
} }
bool PatternLanguage::executeFile(prv::Provider *provider, const fs::path &path, const std::map<std::string, Token::Literal> &envVars, const std::map<std::string, Token::Literal> &inVariables) { bool PatternLanguage::executeFile(prv::Provider *provider, const std::fs::path &path, const std::map<std::string, Token::Literal> &envVars, const std::map<std::string, Token::Literal> &inVariables) {
File file(path, File::Mode::Read); fs::File file(path, fs::File::Mode::Read);
return this->executeString(provider, file.readString(), envVars, inVariables, true); return this->executeString(provider, file.readString(), envVars, inVariables, true);
} }

View File

@ -1,7 +1,7 @@
#include <hex/pattern_language/preprocessor.hpp> #include <hex/pattern_language/preprocessor.hpp>
#include <hex/helpers/fmt.hpp> #include <hex/helpers/fmt.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <hex/helpers/file.hpp> #include <hex/helpers/file.hpp>
#include <filesystem> #include <filesystem>
@ -59,26 +59,26 @@ namespace hex::pl {
} }
offset += 1; offset += 1;
fs::path includePath = includeFile; std::fs::path includePath = includeFile;
if (includeFile[0] != '/') { if (includeFile[0] != '/') {
for (const auto &dir : hex::getPath(ImHexPath::PatternsInclude)) { for (const auto &dir : fs::getDefaultPaths(fs::ImHexPath::PatternsInclude)) {
fs::path tempPath = dir / includePath; std::fs::path tempPath = dir / includePath;
if (fs::is_regular_file(tempPath)) { if (fs::isRegularFile(tempPath)) {
includePath = tempPath; includePath = tempPath;
break; break;
} }
} }
} }
if (!fs::is_regular_file(includePath)) { if (!fs::isRegularFile(includePath)) {
if (includePath.parent_path().filename().string() == "std") if (includePath.parent_path().filename().string() == "std")
throwPreprocessorError(hex::format("{0}: No such file.\n\nThis file might be part of the standard library.\nYou can install the standard library though\nthe Content Store found under Help -> Content Store.", includeFile.c_str()), lineNumber); throwPreprocessorError(hex::format("{0}: No such file.\n\nThis file might be part of the standard library.\nYou can install the standard library though\nthe Content Store found under Help -> Content Store.", includeFile.c_str()), lineNumber);
else else
throwPreprocessorError(hex::format("{0}: No such file", includeFile.c_str()), lineNumber); throwPreprocessorError(hex::format("{0}: No such file", includeFile.c_str()), lineNumber);
} }
File file(includePath, File::Mode::Read); fs::File file(includePath, fs::File::Mode::Read);
if (!file.isValid()) { if (!file.isValid()) {
throwPreprocessorError(hex::format("{0}: Failed to open file", includeFile.c_str()), lineNumber); throwPreprocessorError(hex::format("{0}: Failed to open file", includeFile.c_str()), lineNumber);
} }

View File

@ -37,7 +37,7 @@ namespace hex::prv {
} }
void Provider::save() { } void Provider::save() { }
void Provider::saveAs(const fs::path &path) { } void Provider::saveAs(const std::fs::path &path) { }
void Provider::resize(size_t newSize) { } void Provider::resize(size_t newSize) { }

View File

@ -13,8 +13,8 @@ namespace hex {
std::function<void()> View::s_yesCallback, View::s_noCallback; std::function<void()> View::s_yesCallback, View::s_noCallback;
u32 View::s_selectableFileIndex; u32 View::s_selectableFileIndex;
std::vector<fs::path> View::s_selectableFiles; std::vector<std::fs::path> View::s_selectableFiles;
std::function<void(fs::path)> View::s_selectableFileOpenCallback; std::function<void(std::fs::path)> View::s_selectableFileOpenCallback;
std::vector<nfdfilteritem_t> View::s_selectableFilesValidExtensions; std::vector<nfdfilteritem_t> View::s_selectableFilesValidExtensions;
ImFontAtlas *View::s_fontAtlas; ImFontAtlas *View::s_fontAtlas;
@ -108,7 +108,7 @@ namespace hex {
ImGui::SameLine(); ImGui::SameLine();
if (ImGui::Button("hex.builtin.common.browse"_lang)) { if (ImGui::Button("hex.builtin.common.browse"_lang)) {
hex::openFileBrowser("hex.builtin.common.open"_lang, DialogMode::Open, View::s_selectableFilesValidExtensions, [](const auto &path) { fs::openFileBrowser("hex.builtin.common.open"_lang, fs::DialogMode::Open, View::s_selectableFilesValidExtensions, [](const auto &path) {
View::s_selectableFileOpenCallback(path); View::s_selectableFileOpenCallback(path);
ImGui::CloseCurrentPopup(); ImGui::CloseCurrentPopup();
}); });
@ -145,9 +145,9 @@ namespace hex {
ImHexApi::Tasks::doLater([] { ImGui::OpenPopup("hex.builtin.common.question"_lang); }); ImHexApi::Tasks::doLater([] { ImGui::OpenPopup("hex.builtin.common.question"_lang); });
} }
void View::showFileChooserPopup(const std::vector<fs::path> &paths, const std::vector<nfdfilteritem_t> &validExtensions, const std::function<void(fs::path)> &callback) { void View::showFileChooserPopup(const std::vector<std::fs::path> &paths, const std::vector<nfdfilteritem_t> &validExtensions, const std::function<void(std::fs::path)> &callback) {
if (paths.empty()) { if (paths.empty()) {
hex::openFileBrowser("hex.builtin.common.open"_lang, DialogMode::Open, validExtensions, [callback](const auto &path) { fs::openFileBrowser("hex.builtin.common.open"_lang, fs::DialogMode::Open, validExtensions, [callback](const auto &path) {
callback(path); callback(path);
}); });
} else { } else {

View File

@ -53,7 +53,7 @@ namespace hex {
std::list<std::string> m_popupsToOpen; std::list<std::string> m_popupsToOpen;
std::vector<int> m_pressedKeys; std::vector<int> m_pressedKeys;
fs::path m_imguiSettingsPath; std::fs::path m_imguiSettingsPath;
}; };
} }

View File

@ -7,7 +7,7 @@
#include <hex/pattern_language/patterns/pattern.hpp> #include <hex/pattern_language/patterns/pattern.hpp>
#include <hex/ui/view.hpp> #include <hex/ui/view.hpp>
#include <hex/helpers/net.hpp> #include <hex/helpers/net.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <hex/helpers/logger.hpp> #include <hex/helpers/logger.hpp>
#include <fontawesome_font.h> #include <fontawesome_font.h>
@ -60,23 +60,23 @@ namespace hex::init {
bool result = true; bool result = true;
constexpr std::array paths = { constexpr std::array paths = {
ImHexPath::Patterns, fs::ImHexPath::Patterns,
ImHexPath::PatternsInclude, fs::ImHexPath::PatternsInclude,
ImHexPath::Magic, fs::ImHexPath::Magic,
ImHexPath::Plugins, fs::ImHexPath::Plugins,
ImHexPath::Resources, fs::ImHexPath::Resources,
ImHexPath::Config, fs::ImHexPath::Config,
ImHexPath::Constants, fs::ImHexPath::Constants,
ImHexPath::Yara, fs::ImHexPath::Yara,
ImHexPath::Encodings, fs::ImHexPath::Encodings,
ImHexPath::Python, fs::ImHexPath::Python,
ImHexPath::Logs fs::ImHexPath::Logs
}; };
for (auto path : paths) { for (auto path : paths) {
for (auto &folder : hex::getPath(path, true)) { for (auto &folder : fs::getDefaultPaths(path, true)) {
try { try {
fs::create_directories(folder); fs::createDirectories(folder);
} catch (...) { } catch (...) {
log::error("Failed to create folder {}!", folder.string()); log::error("Failed to create folder {}!", folder.string());
result = false; result = false;
@ -94,11 +94,11 @@ namespace hex::init {
auto fonts = IM_NEW(ImFontAtlas)(); auto fonts = IM_NEW(ImFontAtlas)();
ImFontConfig cfg = {}; ImFontConfig cfg = {};
fs::path fontFile = ContentRegistry::Settings::read("hex.builtin.setting.font", "hex.builtin.setting.font.font_path", ""); std::fs::path fontFile = ContentRegistry::Settings::read("hex.builtin.setting.font", "hex.builtin.setting.font.font_path", "");
// If no custom font has been specified, search for a file called "font.ttf" in one of the resource folders // If no custom font has been specified, search for a file called "font.ttf" in one of the resource folders
if (fontFile.empty()) { if (fontFile.empty()) {
for (const auto &dir : hex::getPath(ImHexPath::Resources)) { for (const auto &dir : fs::getDefaultPaths(fs::ImHexPath::Resources)) {
auto path = dir / "font.ttf"; auto path = dir / "font.ttf";
if (fs::exists(path)) { if (fs::exists(path)) {
log::info("Loading custom front from {}", path.string()); log::info("Loading custom front from {}", path.string());
@ -218,7 +218,7 @@ namespace hex::init {
} }
bool loadPlugins() { bool loadPlugins() {
for (const auto &dir : hex::getPath(ImHexPath::Plugins)) { for (const auto &dir : fs::getDefaultPaths(fs::ImHexPath::Plugins)) {
PluginManager::load(dir); PluginManager::load(dir);
} }

View File

@ -7,7 +7,7 @@
#include <hex/api/imhex_api.hpp> #include <hex/api/imhex_api.hpp>
#include <hex/helpers/utils.hpp> #include <hex/helpers/utils.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <hex/helpers/logger.hpp> #include <hex/helpers/logger.hpp>
#include <hex/helpers/file.hpp> #include <hex/helpers/file.hpp>
@ -123,8 +123,8 @@ namespace hex {
if (!ProjectFile::hasUnsavedChanges()) if (!ProjectFile::hasUnsavedChanges())
return; return;
for (const auto &path : hex::getPath(ImHexPath::Config)) { for (const auto &path : fs::getDefaultPaths(fs::ImHexPath::Config)) {
if (ProjectFile::store((fs::path(path) / CrashBackupFileName).string())) if (ProjectFile::store((std::fs::path(path) / CrashBackupFileName).string()))
break; break;
} }
}); });
@ -352,7 +352,7 @@ namespace hex {
ImGui::TableHeadersRow(); ImGui::TableHeadersRow();
for (const auto &path : hex::getPath(ImHexPath::Plugins, true)) { for (const auto &path : fs::getDefaultPaths(fs::ImHexPath::Plugins, true)) {
ImGui::TableNextRow(); ImGui::TableNextRow();
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextUnformatted(path.string().c_str()); ImGui::TextUnformatted(path.string().c_str());
@ -720,7 +720,7 @@ namespace hex {
handler.UserData = this; handler.UserData = this;
ImGui::GetCurrentContext()->SettingsHandlers.push_back(handler); ImGui::GetCurrentContext()->SettingsHandlers.push_back(handler);
for (const auto &dir : hex::getPath(ImHexPath::Config)) { for (const auto &dir : fs::getDefaultPaths(fs::ImHexPath::Config)) {
if (std::filesystem::exists(dir)) { if (std::filesystem::exists(dir)) {
this->m_imguiSettingsPath = dir / "interface.ini"; this->m_imguiSettingsPath = dir / "interface.ini";
break; break;

View File

@ -27,7 +27,7 @@ namespace hex::plugin::builtin::prv {
void writeRaw(u64 offset, const void *buffer, size_t size) override; void writeRaw(u64 offset, const void *buffer, size_t size) override;
[[nodiscard]] size_t getActualSize() const override; [[nodiscard]] size_t getActualSize() const override;
void setPath(const fs::path &path); void setPath(const std::fs::path &path);
[[nodiscard]] bool open() override; [[nodiscard]] bool open() override;
void close() override; void close() override;
@ -42,7 +42,7 @@ namespace hex::plugin::builtin::prv {
void reloadDrives(); void reloadDrives();
std::set<std::string> m_availableDrives; std::set<std::string> m_availableDrives;
fs::path m_path; std::fs::path m_path;
#if defined(OS_WINDOWS) #if defined(OS_WINDOWS)
HANDLE m_diskHandle = INVALID_HANDLE_VALUE; HANDLE m_diskHandle = INVALID_HANDLE_VALUE;

View File

@ -38,12 +38,12 @@ namespace hex::plugin::builtin::prv {
[[nodiscard]] size_t getActualSize() const override; [[nodiscard]] size_t getActualSize() const override;
void save() override; void save() override;
void saveAs(const fs::path &path) override; void saveAs(const std::fs::path &path) override;
[[nodiscard]] std::string getName() const override; [[nodiscard]] std::string getName() const override;
[[nodiscard]] std::vector<std::pair<std::string, std::string>> getDataInformation() const override; [[nodiscard]] std::vector<std::pair<std::string, std::string>> getDataInformation() const override;
void setPath(const fs::path &path); void setPath(const std::fs::path &path);
[[nodiscard]] bool open() override; [[nodiscard]] bool open() override;
void close() override; void close() override;
@ -56,7 +56,7 @@ namespace hex::plugin::builtin::prv {
int m_file = -1; int m_file = -1;
#endif #endif
fs::path m_path; std::fs::path m_path;
void *m_mappedFile = nullptr; void *m_mappedFile = nullptr;
size_t m_fileSize = 0; size_t m_fileSize = 0;

View File

@ -29,7 +29,7 @@ namespace hex::plugin::builtin::prv {
[[nodiscard]] size_t getActualSize() const override; [[nodiscard]] size_t getActualSize() const override;
void save() override; void save() override;
void saveAs(const fs::path &path) override; void saveAs(const std::fs::path &path) override;
[[nodiscard]] std::string getName() const override; [[nodiscard]] std::string getName() const override;
[[nodiscard]] std::vector<std::pair<std::string, std::string>> getDataInformation() const override; [[nodiscard]] std::vector<std::pair<std::string, std::string>> getDataInformation() const override;

View File

@ -82,7 +82,7 @@ namespace hex::plugin::builtin {
void drawGotoPopup(); void drawGotoPopup();
void drawEditPopup(); void drawEditPopup();
void openFile(const fs::path &path); void openFile(const std::fs::path &path);
void copyBytes() const; void copyBytes() const;
void pasteBytes() const; void pasteBytes() const;

View File

@ -26,7 +26,7 @@ namespace hex::plugin::builtin {
private: private:
pl::PatternLanguage *m_parserRuntime; pl::PatternLanguage *m_parserRuntime;
std::vector<fs::path> m_possiblePatternFiles; std::vector<std::fs::path> m_possiblePatternFiles;
u32 m_selectedPatternFile = 0; u32 m_selectedPatternFile = 0;
bool m_runAutomatically = false; bool m_runAutomatically = false;
@ -77,7 +77,7 @@ namespace hex::plugin::builtin {
void drawEnvVars(ImVec2 size); void drawEnvVars(ImVec2 size);
void drawVariableSettings(ImVec2 size); void drawVariableSettings(ImVec2 size);
void loadPatternFile(const fs::path &path); void loadPatternFile(const std::fs::path &path);
void clearPatterns(); void clearPatterns();
void parsePattern(const std::string &code); void parsePattern(const std::string &code);

View File

@ -4,7 +4,7 @@
#include <hex/ui/view.hpp> #include <hex/ui/view.hpp>
#include <hex/helpers/net.hpp> #include <hex/helpers/net.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <array> #include <array>
#include <future> #include <future>
@ -44,7 +44,7 @@ namespace hex::plugin::builtin {
Net m_net; Net m_net;
std::future<Response<std::string>> m_apiRequest; std::future<Response<std::string>> m_apiRequest;
std::future<Response<void>> m_download; std::future<Response<void>> m_download;
fs::path m_downloadPath; std::fs::path m_downloadPath;
std::vector<StoreEntry> m_patterns, m_includes, m_magics, m_constants, m_yara, m_encodings; std::vector<StoreEntry> m_patterns, m_includes, m_magics, m_constants, m_yara, m_encodings;
@ -53,8 +53,8 @@ namespace hex::plugin::builtin {
void refresh(); void refresh();
void parseResponse(); void parseResponse();
bool download(ImHexPath pathType, const std::string &fileName, const std::string &url, bool update); bool download(fs::ImHexPath pathType, const std::string &fileName, const std::string &url, bool update);
bool remove(ImHexPath pathType, const std::string &fileName); bool remove(fs::ImHexPath pathType, const std::string &fileName);
}; };
} }

View File

@ -254,29 +254,29 @@ namespace hex::plugin::builtin {
ContentRegistry::PatternLanguage::Namespace nsStdFile = { "builtin", "std", "file" }; ContentRegistry::PatternLanguage::Namespace nsStdFile = { "builtin", "std", "file" };
{ {
static u32 fileCounter = 0; static u32 fileCounter = 0;
static std::map<u32, File> openFiles; static std::map<u32, fs::File> openFiles;
/* open(path, mode) */ /* open(path, mode) */
ContentRegistry::PatternLanguage::addDangerousFunction(nsStdFile, "open", 2, [](Evaluator *ctx, auto params) -> std::optional<Token::Literal> { ContentRegistry::PatternLanguage::addDangerousFunction(nsStdFile, "open", 2, [](Evaluator *ctx, auto params) -> std::optional<Token::Literal> {
const auto path = Token::literalToString(params[0], false); const auto path = Token::literalToString(params[0], false);
const auto modeEnum = Token::literalToUnsigned(params[1]); const auto modeEnum = Token::literalToUnsigned(params[1]);
File::Mode mode; fs::File::Mode mode;
switch (modeEnum) { switch (modeEnum) {
case 1: case 1:
mode = File::Mode::Read; mode = fs::File::Mode::Read;
break; break;
case 2: case 2:
mode = File::Mode::Write; mode = fs::File::Mode::Write;
break; break;
case 3: case 3:
mode = File::Mode::Create; mode = fs::File::Mode::Create;
break; break;
default: default:
LogConsole::abortEvaluation("invalid file open mode"); LogConsole::abortEvaluation("invalid file open mode");
} }
auto file = File(path, mode); fs::File file(path, mode);
if (!file.isValid()) if (!file.isValid())
LogConsole::abortEvaluation(hex::format("failed to open file {}", path)); LogConsole::abortEvaluation(hex::format("failed to open file {}", path));

View File

@ -60,7 +60,7 @@ namespace hex::plugin::builtin::prv {
} }
void DiskProvider::setPath(const fs::path &path) { void DiskProvider::setPath(const std::fs::path &path) {
this->m_path = path; this->m_path = path;
} }

View File

@ -1,6 +1,5 @@
#include "content/providers/file_provider.hpp" #include "content/providers/file_provider.hpp"
#include <ctime>
#include <cstring> #include <cstring>
#include <hex/api/localization.hpp> #include <hex/api/localization.hpp>
@ -83,8 +82,8 @@ namespace hex::plugin::builtin::prv {
this->applyPatches(); this->applyPatches();
} }
void FileProvider::saveAs(const fs::path &path) { void FileProvider::saveAs(const std::fs::path &path) {
File file(path, File::Mode::Create); fs::File file(path, fs::File::Mode::Create);
if (file.isValid()) { if (file.isValid()) {
auto provider = ImHexApi::Provider::get(); auto provider = ImHexApi::Provider::get();
@ -106,7 +105,7 @@ namespace hex::plugin::builtin::prv {
this->close(); this->close();
{ {
auto file = File(this->m_path, File::Mode::Write); fs::File file(this->m_path, fs::File::Mode::Write);
file.setSize(newSize); file.setSize(newSize);
this->m_fileSize = file.getSize(); this->m_fileSize = file.getSize();
@ -141,7 +140,7 @@ namespace hex::plugin::builtin::prv {
} }
std::string FileProvider::getName() const { std::string FileProvider::getName() const {
return fs::path(this->m_path).filename().string(); return std::fs::path(this->m_path).filename().string();
} }
std::vector<std::pair<std::string, std::string>> FileProvider::getDataInformation() const { std::vector<std::pair<std::string, std::string>> FileProvider::getDataInformation() const {
@ -159,7 +158,7 @@ namespace hex::plugin::builtin::prv {
return result; return result;
} }
void FileProvider::setPath(const fs::path &path) { void FileProvider::setPath(const std::fs::path &path) {
this->m_path = path; this->m_path = path;
} }

View File

@ -217,7 +217,7 @@ namespace hex::plugin::builtin::prv {
this->applyPatches(); this->applyPatches();
} }
void GDBProvider::saveAs(const fs::path &path) { void GDBProvider::saveAs(const std::fs::path &path) {
} }
size_t GDBProvider::getActualSize() const { size_t GDBProvider::getActualSize() const {

View File

@ -238,10 +238,10 @@ namespace hex::plugin::builtin {
ImGui::SameLine(); ImGui::SameLine();
if (ImGui::IconButton(ICON_VS_FOLDER_OPENED, ImGui::GetStyleColorVec4(ImGuiCol_Text))) { if (ImGui::IconButton(ICON_VS_FOLDER_OPENED, ImGui::GetStyleColorVec4(ImGuiCol_Text))) {
return hex::openFileBrowser("hex.builtin.setting.font.font_path", DialogMode::Open, { return fs::openFileBrowser("hex.builtin.setting.font.font_path", fs::DialogMode::Open, {
{"TTF Font", "ttf"} {"TTF Font", "ttf"}
}, },
[&](const fs::path &path) { [&](const std::fs::path &path) {
fontPath = path.string(); fontPath = path.string();
setting = fontPath; setting = fontPath;
}); });
@ -294,7 +294,7 @@ namespace hex::plugin::builtin {
ImGui::BeginGroup(); ImGui::BeginGroup();
if (ImGui::IconButton(ICON_VS_NEW_FOLDER, ImGui::GetCustomColorVec4(ImGuiCustomCol_DescButton), ImVec2(30, 30))) { if (ImGui::IconButton(ICON_VS_NEW_FOLDER, ImGui::GetCustomColorVec4(ImGuiCustomCol_DescButton), ImVec2(30, 30))) {
hex::openFileBrowser("Select include folder", hex::DialogMode::Folder, {}, [&](fs::path path) { fs::openFileBrowser("Select include folder", fs::DialogMode::Folder, {}, [&](std::fs::path path) {
auto pathStr = path.string(); auto pathStr = path.string();
if (std::find(folders.begin(), folders.end(), pathStr) == folders.end()) { if (std::find(folders.begin(), folders.end(), pathStr) == folders.end()) {

View File

@ -6,7 +6,7 @@
#include <hex/helpers/fmt.hpp> #include <hex/helpers/fmt.hpp>
#include <hex/helpers/file.hpp> #include <hex/helpers/file.hpp>
#include <hex/helpers/literals.hpp> #include <hex/helpers/literals.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <hex/api/localization.hpp> #include <hex/api/localization.hpp>
#include <hex/ui/view.hpp> #include <hex/ui/view.hpp>
@ -571,7 +571,7 @@ namespace hex::plugin::builtin {
static hex::Net net; static hex::Net net;
static std::future<Response<std::string>> uploadProcess; static std::future<Response<std::string>> uploadProcess;
static fs::path currFile; static std::fs::path currFile;
static std::vector<UploadedFile> links; static std::vector<UploadedFile> links;
bool uploading = uploadProcess.valid() && uploadProcess.wait_for(0s) != std::future_status::ready; bool uploading = uploadProcess.valid() && uploadProcess.wait_for(0s) != std::future_status::ready;
@ -579,7 +579,7 @@ namespace hex::plugin::builtin {
ImGui::Header("hex.builtin.tools.file_uploader.control"_lang, true); ImGui::Header("hex.builtin.tools.file_uploader.control"_lang, true);
if (!uploading) { if (!uploading) {
if (ImGui::Button("hex.builtin.tools.file_uploader.upload"_lang)) { if (ImGui::Button("hex.builtin.tools.file_uploader.upload"_lang)) {
hex::openFileBrowser("hex.builtin.tools.file_uploader.done"_lang, DialogMode::Open, {}, [&](auto path) { fs::openFileBrowser("hex.builtin.tools.file_uploader.done"_lang, fs::DialogMode::Open, {}, [&](auto path) {
uploadProcess = net.uploadFile("https://api.anonfiles.com/upload", path); uploadProcess = net.uploadFile("https://api.anonfiles.com/upload", path);
currFile = path; currFile = path;
}); });
@ -744,7 +744,7 @@ namespace hex::plugin::builtin {
ImGui::InputText("##path", selectedFile); ImGui::InputText("##path", selectedFile);
ImGui::SameLine(); ImGui::SameLine();
if (ImGui::Button("...")) { if (ImGui::Button("...")) {
hex::openFileBrowser("hex.builtin.tools.file_tools.shredder.picker"_lang, DialogMode::Open, {}, [](const auto &path) { fs::openFileBrowser("hex.builtin.tools.file_tools.shredder.picker"_lang, fs::DialogMode::Open, {}, [](const auto &path) {
selectedFile = path.string(); selectedFile = path.string();
}); });
} }
@ -768,7 +768,7 @@ namespace hex::plugin::builtin {
shredding = false; shredding = false;
selectedFile.clear(); selectedFile.clear();
}; };
File file(selectedFile, File::Mode::Write); fs::File file(selectedFile, fs::File::Mode::Write);
if (!file.isValid()) { if (!file.isValid()) {
View::showErrorPopup("hex.builtin.tools.file_tools.shredder.error.open"_lang); View::showErrorPopup("hex.builtin.tools.file_tools.shredder.error.open"_lang);
@ -886,7 +886,7 @@ namespace hex::plugin::builtin {
ImGui::InputText("##path", selectedFile); ImGui::InputText("##path", selectedFile);
ImGui::SameLine(); ImGui::SameLine();
if (ImGui::Button("...##input")) { if (ImGui::Button("...##input")) {
hex::openFileBrowser("hex.builtin.tools.file_tools.splitter.picker.input"_lang, DialogMode::Open, {}, [](const auto &path) { fs::openFileBrowser("hex.builtin.tools.file_tools.splitter.picker.input"_lang, fs::DialogMode::Open, {}, [](const auto &path) {
selectedFile = path.string(); selectedFile = path.string();
}); });
} }
@ -896,7 +896,7 @@ namespace hex::plugin::builtin {
ImGui::InputText("##base_path", baseOutputPath); ImGui::InputText("##base_path", baseOutputPath);
ImGui::SameLine(); ImGui::SameLine();
if (ImGui::Button("...##output")) { if (ImGui::Button("...##output")) {
hex::openFileBrowser("hex.builtin.tools.file_tools.splitter.picker.output"_lang, DialogMode::Save, {}, [](const auto &path) { fs::openFileBrowser("hex.builtin.tools.file_tools.splitter.picker.output"_lang, fs::DialogMode::Save, {}, [](const auto &path) {
baseOutputPath = path.string(); baseOutputPath = path.string();
}); });
} }
@ -934,7 +934,7 @@ namespace hex::plugin::builtin {
selectedFile.clear(); selectedFile.clear();
baseOutputPath.clear(); baseOutputPath.clear();
}; };
File file(selectedFile, File::Mode::Read); fs::File file(selectedFile, fs::File::Mode::Read);
if (!file.isValid()) { if (!file.isValid()) {
View::showErrorPopup("hex.builtin.tools.file_tools.splitter.error.open"_lang); View::showErrorPopup("hex.builtin.tools.file_tools.splitter.error.open"_lang);
@ -951,7 +951,7 @@ namespace hex::plugin::builtin {
for (u64 offset = 0; offset < file.getSize(); offset += splitSize) { for (u64 offset = 0; offset < file.getSize(); offset += splitSize) {
task.update(offset); task.update(offset);
File partFile(baseOutputPath + hex::format(".{:05}", index), File::Mode::Create); fs::File partFile(baseOutputPath + hex::format(".{:05}", index), fs::File::Mode::Create);
if (!partFile.isValid()) { if (!partFile.isValid()) {
View::showErrorPopup(hex::format("hex.builtin.tools.file_tools.splitter.error.create"_lang, index)); View::showErrorPopup(hex::format("hex.builtin.tools.file_tools.splitter.error.create"_lang, index));
@ -991,7 +991,7 @@ namespace hex::plugin::builtin {
i32 index = 0; i32 index = 0;
for (auto &file : files) { for (auto &file : files) {
if (ImGui::Selectable(fs::path(file).filename().string().c_str(), index == selectedIndex)) if (ImGui::Selectable(std::fs::path(file).filename().string().c_str(), index == selectedIndex))
selectedIndex = index; selectedIndex = index;
index++; index++;
} }
@ -1025,7 +1025,7 @@ namespace hex::plugin::builtin {
ImGui::BeginDisabled(combining); ImGui::BeginDisabled(combining);
{ {
if (ImGui::Button("hex.builtin.tools.file_tools.combiner.add"_lang)) { if (ImGui::Button("hex.builtin.tools.file_tools.combiner.add"_lang)) {
hex::openFileBrowser("hex.builtin.tools.file_tools.combiner.add.picker"_lang, DialogMode::Open, {}, [](const auto &path) { fs::openFileBrowser("hex.builtin.tools.file_tools.combiner.add.picker"_lang, fs::DialogMode::Open, {}, [](const auto &path) {
files.push_back(path.string()); files.push_back(path.string());
}); });
} }
@ -1049,7 +1049,7 @@ namespace hex::plugin::builtin {
ImGui::InputText("##output_path", outputPath); ImGui::InputText("##output_path", outputPath);
ImGui::SameLine(); ImGui::SameLine();
if (ImGui::Button("...")) { if (ImGui::Button("...")) {
hex::openFileBrowser("hex.builtin.tools.file_tools.combiner.output.picker"_lang, DialogMode::Save, {}, [](const auto &path) { fs::openFileBrowser("hex.builtin.tools.file_tools.combiner.output.picker"_lang, fs::DialogMode::Save, {}, [](const auto &path) {
outputPath = path.string(); outputPath = path.string();
}); });
} }
@ -1069,7 +1069,7 @@ namespace hex::plugin::builtin {
std::thread([] { std::thread([] {
ON_SCOPE_EXIT { combining = false; }; ON_SCOPE_EXIT { combining = false; };
File output(outputPath, File::Mode::Create); fs::File output(outputPath, fs::File::Mode::Create);
if (!output.isValid()) { if (!output.isValid()) {
View::showErrorPopup("hex.builtin.tools.file_tools.combiner.error.open_output"_lang); View::showErrorPopup("hex.builtin.tools.file_tools.combiner.error.open_output"_lang);
@ -1083,9 +1083,9 @@ namespace hex::plugin::builtin {
task.update(fileIndex); task.update(fileIndex);
fileIndex++; fileIndex++;
File input(file, File::Mode::Read); fs::File input(file, fs::File::Mode::Read);
if (!input.isValid()) { if (!input.isValid()) {
View::showErrorPopup(hex::format("hex.builtin.tools.file_tools.combiner.open_input"_lang, fs::path(file).filename().string())); View::showErrorPopup(hex::format("hex.builtin.tools.file_tools.combiner.open_input"_lang, std::fs::path(file).filename().string()));
return; return;
} }

View File

@ -104,7 +104,7 @@ namespace hex::plugin::builtin {
// Save file as // Save file as
ImGui::Disabled([&provider] { ImGui::Disabled([&provider] {
if (ImGui::ToolBarButton(ICON_VS_SAVE_AS, ImGui::GetCustomColorVec4(ImGuiCustomCol_ToolbarBlue))) if (ImGui::ToolBarButton(ICON_VS_SAVE_AS, ImGui::GetCustomColorVec4(ImGuiCustomCol_ToolbarBlue)))
hex::openFileBrowser("hex.builtin.view.hex_editor.save_as"_lang, DialogMode::Save, {}, [&provider](auto path) { fs::openFileBrowser("hex.builtin.view.hex_editor.save_as"_lang, fs::DialogMode::Save, {}, [&provider](auto path) {
provider->saveAs(path); provider->saveAs(path);
}); });
}, },

View File

@ -1,6 +1,6 @@
#include "content/views/view_constants.hpp" #include "content/views/view_constants.hpp"
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <hex/helpers/logger.hpp> #include <hex/helpers/logger.hpp>
#include <hex/helpers/utils.hpp> #include <hex/helpers/utils.hpp>
@ -24,10 +24,11 @@ namespace hex::plugin::builtin {
this->m_constants.clear(); this->m_constants.clear();
this->m_filterIndices.clear(); this->m_filterIndices.clear();
for (const auto &path : hex::getPath(ImHexPath::Constants)) { for (const auto &path : fs::getDefaultPaths(fs::ImHexPath::Constants)) {
if (!fs::exists(path)) continue; if (!fs::exists(path)) continue;
for (auto &file : fs::directory_iterator(path)) { std::error_code error;
for (auto &file : std::fs::directory_iterator(path, error)) {
if (!file.is_regular_file()) continue; if (!file.is_regular_file()) continue;
try { try {

View File

@ -41,7 +41,7 @@ namespace hex::plugin::builtin {
} }
}); });
EventManager::subscribe<EventFileLoaded>(this, [this](const fs::path &path) { EventManager::subscribe<EventFileLoaded>(this, [this](const std::fs::path &path) {
for (auto &node : this->m_nodes) { for (auto &node : this->m_nodes) {
node->setCurrentOverlay(nullptr); node->setCurrentOverlay(nullptr);
} }
@ -54,22 +54,22 @@ namespace hex::plugin::builtin {
ContentRegistry::Interface::addMenuItem("hex.builtin.menu.file", 3000, [&, this] { ContentRegistry::Interface::addMenuItem("hex.builtin.menu.file", 3000, [&, this] {
if (ImGui::MenuItem("hex.builtin.view.data_processor.menu.file.load_processor"_lang)) { if (ImGui::MenuItem("hex.builtin.view.data_processor.menu.file.load_processor"_lang)) {
hex::openFileBrowser("hex.builtin.view.data_processor.menu.file.load_processor"_lang, DialogMode::Open, { fs::openFileBrowser("hex.builtin.view.data_processor.menu.file.load_processor"_lang, fs::DialogMode::Open, {
{"hex.builtin.view.data_processor.name"_lang, "hexnode"} {"hex.builtin.view.data_processor.name"_lang, "hexnode"}
}, },
[this](const fs::path &path) { [this](const std::fs::path &path) {
File file(path, File::Mode::Read); fs::File file(path, fs::File::Mode::Read);
if (file.isValid()) if (file.isValid())
this->loadNodes(file.readString()); this->loadNodes(file.readString());
}); });
} }
if (ImGui::MenuItem("hex.builtin.view.data_processor.menu.file.save_processor"_lang, nullptr, false, !this->m_nodes.empty())) { if (ImGui::MenuItem("hex.builtin.view.data_processor.menu.file.save_processor"_lang, nullptr, false, !this->m_nodes.empty())) {
hex::openFileBrowser("hex.builtin.view.data_processor.menu.file.save_processor"_lang, DialogMode::Save, { fs::openFileBrowser("hex.builtin.view.data_processor.menu.file.save_processor"_lang, fs::DialogMode::Save, {
{"hex.builtin.view.data_processor.name"_lang, "hexnode"} {"hex.builtin.view.data_processor.name"_lang, "hexnode"}
}, },
[this](const fs::path &path) { [this](const std::fs::path &path) {
File file(path, File::Mode::Create); fs::File file(path, fs::File::Mode::Create);
if (file.isValid()) if (file.isValid())
file.write(this->saveNodes()); file.write(this->saveNodes());
}); });
@ -77,7 +77,7 @@ namespace hex::plugin::builtin {
}); });
ContentRegistry::FileHandler::add({ ".hexnode" }, [this](const auto &path) { ContentRegistry::FileHandler::add({ ".hexnode" }, [this](const auto &path) {
File file(path, File::Mode::Read); fs::File file(path, fs::File::Mode::Read);
if (!file.isValid()) return false; if (!file.isValid()) return false;
this->loadNodes(file.readString()); this->loadNodes(file.readString());

View File

@ -4,7 +4,7 @@
#include <hex/helpers/fmt.hpp> #include <hex/helpers/fmt.hpp>
#include <hex/helpers/logger.hpp> #include <hex/helpers/logger.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <hex/helpers/utils.hpp> #include <hex/helpers/utils.hpp>
#include <romfs/romfs.hpp> #include <romfs/romfs.hpp>
@ -119,15 +119,15 @@ namespace hex::plugin::builtin {
ImGui::TableSetupColumn("Type"); ImGui::TableSetupColumn("Type");
ImGui::TableSetupColumn("Paths"); ImGui::TableSetupColumn("Paths");
constexpr std::array<std::pair<const char *, ImHexPath>, 8> PathTypes = { constexpr std::array<std::pair<const char *, fs::ImHexPath>, 8> PathTypes = {
{{ "Resources", ImHexPath::Resources }, {{ "Resources", fs::ImHexPath::Resources },
{ "Config", ImHexPath::Config }, { "Config", fs::ImHexPath::Config },
{ "Magic", ImHexPath::Magic }, { "Magic", fs::ImHexPath::Magic },
{ "Patterns", ImHexPath::Patterns }, { "Patterns", fs::ImHexPath::Patterns },
{ "Patterns Includes", ImHexPath::PatternsInclude }, { "Patterns Includes", fs::ImHexPath::PatternsInclude },
{ "Plugins", ImHexPath::Plugins }, { "Plugins", fs::ImHexPath::Plugins },
{ "Python Scripts", ImHexPath::Python }, { "Python Scripts", fs::ImHexPath::Python },
{ "Yara Patterns", ImHexPath::Yara }} { "Yara Patterns", fs::ImHexPath::Yara }}
}; };
ImGui::TableHeadersRow(); ImGui::TableHeadersRow();
@ -137,7 +137,7 @@ namespace hex::plugin::builtin {
ImGui::TextUnformatted(name); ImGui::TextUnformatted(name);
ImGui::TableNextColumn(); ImGui::TableNextColumn();
for (auto &path : hex::getPath(type)) for (auto &path : fs::getDefaultPaths(type))
ImGui::TextUnformatted(path.string().c_str()); ImGui::TextUnformatted(path.string().c_str());
} }

View File

@ -6,7 +6,7 @@
#include <hex/providers/provider.hpp> #include <hex/providers/provider.hpp>
#include <hex/helpers/crypto.hpp> #include <hex/helpers/crypto.hpp>
#include <hex/helpers/file.hpp> #include <hex/helpers/file.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <hex/helpers/patches.hpp> #include <hex/helpers/patches.hpp>
#include <hex/helpers/project_file_handler.hpp> #include <hex/helpers/project_file_handler.hpp>
#include <hex/helpers/loader_script_handler.hpp> #include <hex/helpers/loader_script_handler.hpp>
@ -267,7 +267,7 @@ namespace hex::plugin::builtin {
} }
static void saveAs() { static void saveAs() {
hex::openFileBrowser("hex.builtin.view.hex_editor.save_as"_lang, DialogMode::Save, {}, [](const auto &path) { fs::openFileBrowser("hex.builtin.view.hex_editor.save_as"_lang, fs::DialogMode::Save, {}, [](const auto &path) {
ImHexApi::Provider::get()->saveAs(path); ImHexApi::Provider::get()->saveAs(path);
}); });
} }
@ -297,7 +297,7 @@ namespace hex::plugin::builtin {
ImGui::InputText("##nolabel", this->m_loaderScriptScriptPath.data(), this->m_loaderScriptScriptPath.length(), ImGuiInputTextFlags_ReadOnly); ImGui::InputText("##nolabel", this->m_loaderScriptScriptPath.data(), this->m_loaderScriptScriptPath.length(), ImGuiInputTextFlags_ReadOnly);
ImGui::SameLine(); ImGui::SameLine();
if (ImGui::Button("hex.builtin.view.hex_editor.script.script"_lang)) { if (ImGui::Button("hex.builtin.view.hex_editor.script.script"_lang)) {
hex::openFileBrowser("hex.builtin.view.hex_editor.script.script.title"_lang, DialogMode::Open, { fs::openFileBrowser("hex.builtin.view.hex_editor.script.script.title"_lang, fs::DialogMode::Open, {
{"Python Script", "py"} {"Python Script", "py"}
}, },
[this](const auto &path) { [this](const auto &path) {
@ -307,7 +307,7 @@ namespace hex::plugin::builtin {
ImGui::InputText("##nolabel", this->m_loaderScriptFilePath.data(), this->m_loaderScriptFilePath.length(), ImGuiInputTextFlags_ReadOnly); ImGui::InputText("##nolabel", this->m_loaderScriptFilePath.data(), this->m_loaderScriptFilePath.length(), ImGuiInputTextFlags_ReadOnly);
ImGui::SameLine(); ImGui::SameLine();
if (ImGui::Button("hex.builtin.view.hex_editor.script.file"_lang)) { if (ImGui::Button("hex.builtin.view.hex_editor.script.file"_lang)) {
hex::openFileBrowser("hex.builtin.view.hex_editor.script.file.title"_lang, DialogMode::Open, {}, [this](const auto &path) { fs::openFileBrowser("hex.builtin.view.hex_editor.script.file.title"_lang, fs::DialogMode::Open, {}, [this](const auto &path) {
this->m_loaderScriptFilePath = path.string(); this->m_loaderScriptFilePath = path.string();
}); });
} }
@ -379,7 +379,7 @@ namespace hex::plugin::builtin {
} }
} }
void ViewHexEditor::openFile(const fs::path &path) { void ViewHexEditor::openFile(const std::fs::path &path) {
hex::prv::Provider *provider = nullptr; hex::prv::Provider *provider = nullptr;
EventManager::post<RequestCreateProvider>("hex.builtin.provider.file", &provider); EventManager::post<RequestCreateProvider>("hex.builtin.provider.file", &provider);
@ -863,10 +863,10 @@ namespace hex::plugin::builtin {
} }
}); });
EventManager::subscribe<RequestOpenWindow>(this, [this](std::string name) { EventManager::subscribe<RequestOpenWindow>(this, [this](const std::string &name) {
if (name == "Create File") { if (name == "Create File") {
hex::openFileBrowser("hex.builtin.view.hex_editor.create_file"_lang, DialogMode::Save, {}, [this](const auto &path) { fs::openFileBrowser("hex.builtin.view.hex_editor.create_file"_lang, fs::DialogMode::Save, {}, [this](const auto &path) {
File file(path, File::Mode::Create); fs::File file(path, fs::File::Mode::Create);
if (!file.isValid()) { if (!file.isValid()) {
View::showErrorPopup("hex.builtin.view.hex_editor.error.create"_lang); View::showErrorPopup("hex.builtin.view.hex_editor.error.create"_lang);
@ -879,12 +879,12 @@ namespace hex::plugin::builtin {
this->getWindowOpenState() = true; this->getWindowOpenState() = true;
}); });
} else if (name == "Open File") { } else if (name == "Open File") {
hex::openFileBrowser("hex.builtin.view.hex_editor.open_file"_lang, DialogMode::Open, {}, [this](const auto &path) { fs::openFileBrowser("hex.builtin.view.hex_editor.open_file"_lang, fs::DialogMode::Open, {}, [this](const auto &path) {
EventManager::post<RequestOpenFile>(path); EventManager::post<RequestOpenFile>(path);
this->getWindowOpenState() = true; this->getWindowOpenState() = true;
}); });
} else if (name == "Open Project") { } else if (name == "Open Project") {
hex::openFileBrowser("hex.builtin.view.hex_editor.open_project"_lang, DialogMode::Open, { fs::openFileBrowser("hex.builtin.view.hex_editor.open_project"_lang, fs::DialogMode::Open, {
{"Project File", "hexproj"} {"Project File", "hexproj"}
}, },
[this](const auto &path) { [this](const auto &path) {
@ -998,7 +998,7 @@ namespace hex::plugin::builtin {
}); });
ShortcutManager::addShortcut(this, CTRL + Keys::O, [] { ShortcutManager::addShortcut(this, CTRL + Keys::O, [] {
hex::openFileBrowser("hex.builtin.view.hex_editor.open_file"_lang, DialogMode::Open, {}, [](const auto &path) { fs::openFileBrowser("hex.builtin.view.hex_editor.open_file"_lang, fs::DialogMode::Open, {}, [](const auto &path) {
EventManager::post<RequestOpenFile>(path); EventManager::post<RequestOpenFile>(path);
}); });
}); });
@ -1057,7 +1057,7 @@ namespace hex::plugin::builtin {
bool providerValid = ImHexApi::Provider::isValid(); bool providerValid = ImHexApi::Provider::isValid();
if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.file.open_project"_lang, "")) { if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.file.open_project"_lang, "")) {
hex::openFileBrowser("hex.builtin.view.hex_editor.menu.file.open_project"_lang, DialogMode::Open, { fs::openFileBrowser("hex.builtin.view.hex_editor.menu.file.open_project"_lang, fs::DialogMode::Open, {
{"Project File", "hexproj"} {"Project File", "hexproj"}
}, },
[](const auto &path) { [](const auto &path) {
@ -1067,10 +1067,10 @@ namespace hex::plugin::builtin {
if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.file.save_project"_lang, "", false, providerValid && provider->isWritable())) { if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.file.save_project"_lang, "", false, providerValid && provider->isWritable())) {
if (ProjectFile::getProjectFilePath() == "") { if (ProjectFile::getProjectFilePath() == "") {
hex::openFileBrowser("hex.builtin.view.hex_editor.save_project"_lang, DialogMode::Save, { fs::openFileBrowser("hex.builtin.view.hex_editor.save_project"_lang, fs::DialogMode::Save, {
{"Project File", "hexproj"} {"Project File", "hexproj"}
}, },
[](fs::path path) { [](std::fs::path path) {
if (path.extension() != ".hexproj") { if (path.extension() != ".hexproj") {
path.replace_extension(".hexproj"); path.replace_extension(".hexproj");
} }
@ -1082,9 +1082,10 @@ namespace hex::plugin::builtin {
} }
if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.file.load_encoding_file"_lang)) { if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.file.load_encoding_file"_lang)) {
std::vector<fs::path> paths; std::vector<std::fs::path> paths;
for (const auto &path : hex::getPath(ImHexPath::Encodings)) { for (const auto &path : fs::getDefaultPaths(fs::ImHexPath::Encodings)) {
for (const auto &entry : fs::recursive_directory_iterator(path)) { std::error_code error;
for (const auto &entry : std::fs::recursive_directory_iterator(path, error)) {
if (!entry.is_regular_file()) continue; if (!entry.is_regular_file()) continue;
paths.push_back(entry); paths.push_back(entry);
@ -1110,8 +1111,8 @@ namespace hex::plugin::builtin {
if (ImGui::BeginMenu("hex.builtin.view.hex_editor.menu.file.import"_lang)) { if (ImGui::BeginMenu("hex.builtin.view.hex_editor.menu.file.import"_lang)) {
if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.file.import.base64"_lang)) { if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.file.import.base64"_lang)) {
hex::openFileBrowser("hex.builtin.view.hex_editor.menu.file.import.base64"_lang, DialogMode::Open, {}, [this](const auto &path) { fs::openFileBrowser("hex.builtin.view.hex_editor.menu.file.import.base64"_lang, fs::DialogMode::Open, {}, [this](const auto &path) {
File file(path, File::Mode::Read); fs::File file(path, fs::File::Mode::Read);
if (!file.isValid()) { if (!file.isValid()) {
View::showErrorPopup("hex.builtin.view.hex_editor.error.open"_lang); View::showErrorPopup("hex.builtin.view.hex_editor.error.open"_lang);
return; return;
@ -1135,12 +1136,12 @@ namespace hex::plugin::builtin {
if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.file.import.ips"_lang, nullptr, false, !this->m_processingImportExport)) { if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.file.import.ips"_lang, nullptr, false, !this->m_processingImportExport)) {
hex::openFileBrowser("hex.builtin.view.hex_editor.open_file"_lang, DialogMode::Open, {}, [this](const auto &path) { fs::openFileBrowser("hex.builtin.view.hex_editor.open_file"_lang, fs::DialogMode::Open, {}, [this](const auto &path) {
this->m_processingImportExport = true; this->m_processingImportExport = true;
std::thread([this, path] { std::thread([this, path] {
auto task = ImHexApi::Tasks::createTask("hex.builtin.view.hex_editor.processing", 0); auto task = ImHexApi::Tasks::createTask("hex.builtin.view.hex_editor.processing", 0);
auto patchData = File(path, File::Mode::Read).readBytes(); auto patchData = fs::File(path, fs::File::Mode::Read).readBytes();
auto patch = hex::loadIPSPatch(patchData); auto patch = hex::loadIPSPatch(patchData);
task.setMaxValue(patch.size()); task.setMaxValue(patch.size());
@ -1163,12 +1164,12 @@ namespace hex::plugin::builtin {
} }
if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.file.import.ips32"_lang, nullptr, false, !this->m_processingImportExport)) { if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.file.import.ips32"_lang, nullptr, false, !this->m_processingImportExport)) {
hex::openFileBrowser("hex.builtin.view.hex_editor.open_file"_lang, DialogMode::Open, {}, [this](const auto &path) { fs::openFileBrowser("hex.builtin.view.hex_editor.open_file"_lang, fs::DialogMode::Open, {}, [this](const auto &path) {
this->m_processingImportExport = true; this->m_processingImportExport = true;
std::thread([this, path] { std::thread([this, path] {
auto task = ImHexApi::Tasks::createTask("hex.builtin.view.hex_editor.processing", 0); auto task = ImHexApi::Tasks::createTask("hex.builtin.view.hex_editor.processing", 0);
auto patchData = File(path, File::Mode::Read).readBytes(); auto patchData = fs::File(path, fs::File::Mode::Read).readBytes();
auto patch = hex::loadIPS32Patch(patchData); auto patch = hex::loadIPS32Patch(patchData);
task.setMaxValue(patch.size()); task.setMaxValue(patch.size());
@ -1218,8 +1219,8 @@ namespace hex::plugin::builtin {
this->m_processingImportExport = false; this->m_processingImportExport = false;
ImHexApi::Tasks::doLater([this] { ImHexApi::Tasks::doLater([this] {
hex::openFileBrowser("hex.builtin.view.hex_editor.menu.file.export.title"_lang, DialogMode::Save, {}, [this](const auto &path) { fs::openFileBrowser("hex.builtin.view.hex_editor.menu.file.export.title"_lang, fs::DialogMode::Save, {}, [this](const auto &path) {
auto file = File(path, File::Mode::Create); auto file = fs::File(path, fs::File::Mode::Create);
if (!file.isValid()) { if (!file.isValid()) {
View::showErrorPopup("hex.builtin.view.hex_editor.error.create"_lang); View::showErrorPopup("hex.builtin.view.hex_editor.error.create"_lang);
return; return;
@ -1247,8 +1248,8 @@ namespace hex::plugin::builtin {
this->m_processingImportExport = false; this->m_processingImportExport = false;
ImHexApi::Tasks::doLater([this] { ImHexApi::Tasks::doLater([this] {
hex::openFileBrowser("hex.builtin.view.hex_editor.menu.file.export.title"_lang, DialogMode::Save, {}, [this](const auto &path) { fs::openFileBrowser("hex.builtin.view.hex_editor.menu.file.export.title"_lang, fs::DialogMode::Save, {}, [this](const auto &path) {
auto file = File(path, File::Mode::Create); auto file = fs::File(path, fs::File::Mode::Create);
if (!file.isValid()) { if (!file.isValid()) {
View::showErrorPopup("hex.builtin.view.hex_editor.error.create"_lang); View::showErrorPopup("hex.builtin.view.hex_editor.error.create"_lang);
return; return;

View File

@ -3,7 +3,7 @@
#include <hex/api/content_registry.hpp> #include <hex/api/content_registry.hpp>
#include <hex/providers/provider.hpp> #include <hex/providers/provider.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <hex/helpers/fmt.hpp> #include <hex/helpers/fmt.hpp>
#include <hex/helpers/literals.hpp> #include <hex/helpers/literals.hpp>
@ -46,9 +46,8 @@ namespace hex::plugin::builtin {
}); });
ContentRegistry::FileHandler::add({ ".mgc" }, [](const auto &path) { ContentRegistry::FileHandler::add({ ".mgc" }, [](const auto &path) {
for (const auto &destPath : hex::getPath(ImHexPath::Magic)) { for (const auto &destPath : fs::getDefaultPaths(fs::ImHexPath::Magic)) {
std::error_code error; if (fs::copyFile(path, destPath / path.filename(), std::fs::copy_options::overwrite_existing)) {
if (fs::copy_file(path, destPath / path.filename(), fs::copy_options::overwrite_existing, error)) {
View::showMessagePopup("hex.builtin.view.information.magic_db_added"_lang); View::showMessagePopup("hex.builtin.view.information.magic_db_added"_lang);
return true; return true;
} }

View File

@ -8,7 +8,7 @@
#include <hex/pattern_language/ast/ast_node_type_decl.hpp> #include <hex/pattern_language/ast/ast_node_type_decl.hpp>
#include <hex/pattern_language/ast/ast_node_builtin_type.hpp> #include <hex/pattern_language/ast/ast_node_builtin_type.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <hex/helpers/utils.hpp> #include <hex/helpers/utils.hpp>
#include <hex/helpers/file.hpp> #include <hex/helpers/file.hpp>
#include <hex/helpers/project_file_handler.hpp> #include <hex/helpers/project_file_handler.hpp>
@ -100,7 +100,7 @@ namespace hex::plugin::builtin {
this->m_textEditor.InsertText(code); this->m_textEditor.InsertText(code);
}); });
EventManager::subscribe<EventFileLoaded>(this, [this](const fs::path &path) { EventManager::subscribe<EventFileLoaded>(this, [this](const std::fs::path &path) {
if (!ContentRegistry::Settings::read("hex.builtin.setting.general", "hex.builtin.setting.general.auto_load_patterns", 1)) if (!ContentRegistry::Settings::read("hex.builtin.setting.general", "hex.builtin.setting.general.auto_load_patterns", 1))
return; return;
@ -124,13 +124,13 @@ namespace hex::plugin::builtin {
this->m_possiblePatternFiles.clear(); this->m_possiblePatternFiles.clear();
std::error_code errorCode; std::error_code errorCode;
for (const auto &dir : hex::getPath(ImHexPath::Patterns)) { for (const auto &dir : fs::getDefaultPaths(fs::ImHexPath::Patterns)) {
for (auto &entry : fs::directory_iterator(dir, errorCode)) { for (auto &entry : std::fs::directory_iterator(dir, errorCode)) {
foundCorrectType = false; foundCorrectType = false;
if (!entry.is_regular_file()) if (!entry.is_regular_file())
continue; continue;
File file(entry.path().string(), File::Mode::Read); fs::File file(entry.path().string(), fs::File::Mode::Read);
if (!file.isValid()) if (!file.isValid())
continue; continue;
@ -181,8 +181,8 @@ namespace hex::plugin::builtin {
}); });
} }
ContentRegistry::FileHandler::add({ ".hexpat", ".pat" }, [](const fs::path &path) -> bool { ContentRegistry::FileHandler::add({ ".hexpat", ".pat" }, [](const std::fs::path &path) -> bool {
File file(path.string(), File::Mode::Read); fs::File file(path.string(), fs::File::Mode::Read);
if (file.isValid()) { if (file.isValid()) {
EventManager::post<RequestSetPatternLanguageCode>(file.readString()); EventManager::post<RequestSetPatternLanguageCode>(file.readString());
@ -195,12 +195,13 @@ namespace hex::plugin::builtin {
ContentRegistry::Interface::addMenuItem("hex.builtin.menu.file", 2000, [&, this] { ContentRegistry::Interface::addMenuItem("hex.builtin.menu.file", 2000, [&, this] {
if (ImGui::MenuItem("hex.builtin.view.pattern_editor.menu.file.load_pattern"_lang)) { if (ImGui::MenuItem("hex.builtin.view.pattern_editor.menu.file.load_pattern"_lang)) {
std::vector<fs::path> paths; std::vector<std::fs::path> paths;
for (const auto &imhexPath : hex::getPath(ImHexPath::Patterns)) { for (const auto &imhexPath : fs::getDefaultPaths(fs::ImHexPath::Patterns)) {
if (!fs::exists(imhexPath)) continue; if (!fs::exists(imhexPath)) continue;
for (auto &entry : fs::recursive_directory_iterator(imhexPath)) { std::error_code error;
for (auto &entry : std::fs::recursive_directory_iterator(imhexPath, error)) {
if (entry.is_regular_file() && entry.path().extension() == ".hexpat") { if (entry.is_regular_file() && entry.path().extension() == ".hexpat") {
paths.push_back(entry.path()); paths.push_back(entry.path());
} }
@ -210,17 +211,17 @@ namespace hex::plugin::builtin {
View::showFileChooserPopup(paths, { View::showFileChooserPopup(paths, {
{"Pattern File", "hexpat"} {"Pattern File", "hexpat"}
}, },
[this](const fs::path &path) { [this](const std::fs::path &path) {
this->loadPatternFile(path); this->loadPatternFile(path);
}); });
} }
if (ImGui::MenuItem("hex.builtin.view.pattern_editor.menu.file.save_pattern"_lang)) { if (ImGui::MenuItem("hex.builtin.view.pattern_editor.menu.file.save_pattern"_lang)) {
hex::openFileBrowser("hex.builtin.view.pattern_editor.menu.file.save_pattern"_lang, DialogMode::Save, { fs::openFileBrowser("hex.builtin.view.pattern_editor.menu.file.save_pattern"_lang, fs::DialogMode::Save, {
{"Pattern", "hexpat"} {"Pattern", "hexpat"}
}, },
[this](const auto &path) { [this](const auto &path) {
File file(path, File::Mode::Create); fs::File file(path, fs::File::Mode::Create);
file.write(this->m_textEditor.GetText()); file.write(this->m_textEditor.GetText());
}); });
@ -549,7 +550,7 @@ namespace hex::plugin::builtin {
entries.resize(this->m_possiblePatternFiles.size()); entries.resize(this->m_possiblePatternFiles.size());
for (u32 i = 0; i < entries.size(); i++) { for (u32 i = 0; i < entries.size(); i++) {
entries[i] = fs::path(this->m_possiblePatternFiles[i]).filename().string(); entries[i] = std::fs::path(this->m_possiblePatternFiles[i]).filename().string();
} }
if (ImGui::BeginListBox("##patterns_accept", ImVec2(-FLT_MIN, 0))) { if (ImGui::BeginListBox("##patterns_accept", ImVec2(-FLT_MIN, 0))) {
@ -580,8 +581,8 @@ namespace hex::plugin::builtin {
} }
void ViewPatternEditor::loadPatternFile(const fs::path &path) { void ViewPatternEditor::loadPatternFile(const std::fs::path &path) {
File file(path, File::Mode::Read); fs::File file(path, fs::File::Mode::Read);
if (file.isValid()) { if (file.isValid()) {
auto code = file.readString(); auto code = file.readString();

View File

@ -11,7 +11,7 @@
#include <hex/helpers/logger.hpp> #include <hex/helpers/logger.hpp>
#include <hex/helpers/magic.hpp> #include <hex/helpers/magic.hpp>
#include <hex/helpers/file.hpp> #include <hex/helpers/file.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <fstream> #include <fstream>
#include <filesystem> #include <filesystem>
@ -44,7 +44,7 @@ namespace hex::plugin::builtin {
this->refresh(); this->refresh();
} }
auto drawTab = [this](auto title, ImHexPath pathType, auto &content, const std::function<void(const StoreEntry &)> &downloadDoneCallback) { auto drawTab = [this](auto title, fs::ImHexPath pathType, auto &content, const std::function<void(const StoreEntry &)> &downloadDoneCallback) {
if (ImGui::BeginTabItem(title)) { if (ImGui::BeginTabItem(title)) {
if (ImGui::BeginTable("##pattern_language", 3, ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_RowBg)) { if (ImGui::BeginTable("##pattern_language", 3, ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_RowBg)) {
ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableSetupScrollFreeze(0, 1);
@ -84,14 +84,14 @@ namespace hex::plugin::builtin {
mtar_header_t header; mtar_header_t header;
auto extractBasePath = this->m_downloadPath.parent_path() / this->m_downloadPath.stem(); auto extractBasePath = this->m_downloadPath.parent_path() / this->m_downloadPath.stem();
while (mtar_read_header(&ctx, &header) != MTAR_ENULLRECORD) { while (mtar_read_header(&ctx, &header) != MTAR_ENULLRECORD) {
auto filePath = extractBasePath / fs::path(header.name); auto filePath = extractBasePath / std::fs::path(header.name);
if (filePath.filename() == "@PaxHeader") { if (filePath.filename() == "@PaxHeader") {
mtar_next(&ctx); mtar_next(&ctx);
continue; continue;
} }
fs::create_directories(filePath.parent_path()); fs::createDirectories(filePath.parent_path());
File outputFile(filePath.string(), File::Mode::Create); fs::File outputFile(filePath.string(), fs::File::Mode::Create);
std::vector<u8> buffer(0x10000); std::vector<u8> buffer(0x10000);
for (u64 offset = 0; offset < header.size; offset += buffer.size()) { for (u64 offset = 0; offset < header.size; offset += buffer.size()) {
@ -142,12 +142,12 @@ namespace hex::plugin::builtin {
}; };
if (ImGui::BeginTabBar("storeTabs")) { if (ImGui::BeginTabBar("storeTabs")) {
drawTab("hex.builtin.view.store.tab.patterns"_lang, ImHexPath::Patterns, this->m_patterns, [](auto) {}); drawTab("hex.builtin.view.store.tab.patterns"_lang, fs::ImHexPath::Patterns, this->m_patterns, [](auto) {});
drawTab("hex.builtin.view.store.tab.libraries"_lang, ImHexPath::PatternsInclude, this->m_includes, [](auto) {}); drawTab("hex.builtin.view.store.tab.libraries"_lang, fs::ImHexPath::PatternsInclude, this->m_includes, [](auto) {});
drawTab("hex.builtin.view.store.tab.magics"_lang, ImHexPath::Magic, this->m_magics, [](auto) { magic::compile(); }); drawTab("hex.builtin.view.store.tab.magics"_lang, fs::ImHexPath::Magic, this->m_magics, [](auto) { magic::compile(); });
drawTab("hex.builtin.view.store.tab.constants"_lang, ImHexPath::Constants, this->m_constants, [](auto) {}); drawTab("hex.builtin.view.store.tab.constants"_lang, fs::ImHexPath::Constants, this->m_constants, [](auto) {});
drawTab("hex.builtin.view.store.tab.encodings"_lang, ImHexPath::Encodings, this->m_encodings, [](auto) {}); drawTab("hex.builtin.view.store.tab.encodings"_lang, fs::ImHexPath::Encodings, this->m_encodings, [](auto) {});
drawTab("hex.builtin.view.store.tab.yara"_lang, ImHexPath::Yara, this->m_yara, [](auto) {}); drawTab("hex.builtin.view.store.tab.yara"_lang, fs::ImHexPath::Yara, this->m_yara, [](auto) {});
ImGui::EndTabBar(); ImGui::EndTabBar();
} }
@ -169,7 +169,7 @@ namespace hex::plugin::builtin {
if (response.code == 200) { if (response.code == 200) {
auto json = nlohmann::json::parse(response.body); auto json = nlohmann::json::parse(response.body);
auto parseStoreEntries = [](auto storeJson, const std::string &name, ImHexPath pathType, std::vector<StoreEntry> &results) { auto parseStoreEntries = [](auto storeJson, const std::string &name, fs::ImHexPath pathType, std::vector<StoreEntry> &results) {
// Check if the response handles the type of files // Check if the response handles the type of files
if (storeJson.contains(name)) { if (storeJson.contains(name)) {
@ -182,15 +182,15 @@ namespace hex::plugin::builtin {
StoreEntry storeEntry = { entry["name"], entry["desc"], entry["file"], entry["url"], entry["hash"], entry["folder"], false, false, false }; StoreEntry storeEntry = { entry["name"], entry["desc"], entry["file"], entry["url"], entry["hash"], entry["folder"], false, false, false };
// Check if file is installed already or has an update available // Check if file is installed already or has an update available
for (const auto &folder : hex::getPath(pathType)) { for (const auto &folder : fs::getDefaultPaths(pathType)) {
auto path = folder / fs::path(storeEntry.fileName); auto path = folder / std::fs::path(storeEntry.fileName);
if (fs::exists(path) && hex::isPathWritable(folder)) { if (fs::exists(path) && fs::isPathWritable(folder)) {
storeEntry.installed = true; storeEntry.installed = true;
std::ifstream file(path, std::ios::in | std::ios::binary); std::ifstream file(path, std::ios::in | std::ios::binary);
std::vector<u8> data(fs::file_size(path), 0x00); std::vector<u8> data(fs::getFileSize(path), 0x00);
file.read(reinterpret_cast<char *>(data.data()), data.size()); file.read(reinterpret_cast<char *>(data.data()), data.size());
auto fileHash = crypt::sha256(data); auto fileHash = crypt::sha256(data);
@ -207,12 +207,12 @@ namespace hex::plugin::builtin {
} }
}; };
parseStoreEntries(json, "patterns", ImHexPath::Patterns, this->m_patterns); parseStoreEntries(json, "patterns", fs::ImHexPath::Patterns, this->m_patterns);
parseStoreEntries(json, "includes", ImHexPath::PatternsInclude, this->m_includes); parseStoreEntries(json, "includes", fs::ImHexPath::PatternsInclude, this->m_includes);
parseStoreEntries(json, "magic", ImHexPath::Magic, this->m_magics); parseStoreEntries(json, "magic", fs::ImHexPath::Magic, this->m_magics);
parseStoreEntries(json, "constants", ImHexPath::Constants, this->m_constants); parseStoreEntries(json, "constants", fs::ImHexPath::Constants, this->m_constants);
parseStoreEntries(json, "yara", ImHexPath::Yara, this->m_yara); parseStoreEntries(json, "yara", fs::ImHexPath::Yara, this->m_yara);
parseStoreEntries(json, "encodings", ImHexPath::Encodings, this->m_encodings); parseStoreEntries(json, "encodings", fs::ImHexPath::Encodings, this->m_encodings);
} }
this->m_apiRequest = {}; this->m_apiRequest = {};
} }
@ -234,13 +234,13 @@ namespace hex::plugin::builtin {
} }
} }
bool ViewStore::download(ImHexPath pathType, const std::string &fileName, const std::string &url, bool update) { bool ViewStore::download(fs::ImHexPath pathType, const std::string &fileName, const std::string &url, bool update) {
bool downloading = false; bool downloading = false;
for (const auto &path : hex::getPath(pathType)) { for (const auto &path : fs::getDefaultPaths(pathType)) {
if (!hex::isPathWritable(path)) if (!fs::isPathWritable(path))
continue; continue;
auto fullPath = path / fs::path(fileName); auto fullPath = path / std::fs::path(fileName);
if (!update || fs::exists(fullPath)) { if (!update || fs::exists(fullPath)) {
downloading = true; downloading = true;
@ -258,13 +258,11 @@ namespace hex::plugin::builtin {
return true; return true;
} }
bool ViewStore::remove(ImHexPath pathType, const std::string &fileName) { bool ViewStore::remove(fs::ImHexPath pathType, const std::string &fileName) {
bool removed = false; bool removed = false;
for (const auto &path : hex::getPath(pathType)) { for (const auto &path : fs::getDefaultPaths(pathType)) {
std::error_code error; bool removedFile = fs::remove(path / std::fs::path(fileName));
bool removedFolder = fs::remove(path / std::fs::path(fileName).stem());
bool removedFile = fs::remove(path / fs::path(fileName), error);
bool removedFolder = fs::remove(path / fs::path(fileName).stem(), error);
removed = removed || removedFile || removedFolder; removed = removed || removedFile || removedFolder;
} }

View File

@ -5,14 +5,14 @@
#include <hex/providers/provider.hpp> #include <hex/providers/provider.hpp>
#include <hex/helpers/utils.hpp> #include <hex/helpers/utils.hpp>
#include <hex/helpers/file.hpp> #include <hex/helpers/file.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <hex/helpers/logger.hpp> #include <hex/helpers/logger.hpp>
#include <yara.h> #include <yara.h>
#include <filesystem> #include <filesystem>
#include <thread> #include <thread>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
namespace hex::plugin::builtin { namespace hex::plugin::builtin {
@ -22,9 +22,8 @@ namespace hex::plugin::builtin {
this->reloadRules(); this->reloadRules();
ContentRegistry::FileHandler::add({ ".yar" }, [](const auto &path) { ContentRegistry::FileHandler::add({ ".yar" }, [](const auto &path) {
for (const auto &destPath : hex::getPath(ImHexPath::Yara)) { for (const auto &destPath : fs::getDefaultPaths(fs::ImHexPath::Yara)) {
std::error_code error; if (fs::copyFile(path, destPath / path.filename(), std::fs::copy_options::overwrite_existing)) {
if (fs::copy_file(path, destPath / path.filename(), fs::copy_options::overwrite_existing, error)) {
View::showMessagePopup("hex.builtin.view.yara.rule_added"_lang); View::showMessagePopup("hex.builtin.view.yara.rule_added"_lang);
return true; return true;
} }
@ -134,13 +133,14 @@ namespace hex::plugin::builtin {
void ViewYara::reloadRules() { void ViewYara::reloadRules() {
this->m_rules.clear(); this->m_rules.clear();
for (const auto path : hex::getPath(ImHexPath::Yara)) { for (const auto path : fs::getDefaultPaths(fs::ImHexPath::Yara)) {
if (!fs::exists(path)) if (!fs::exists(path))
continue; continue;
for (const auto &entry : fs::recursive_directory_iterator(path)) { std::error_code error;
for (const auto &entry : std::fs::recursive_directory_iterator(path, error)) {
if (entry.is_regular_file() && entry.path().extension() == ".yar") { if (entry.is_regular_file() && entry.path().extension() == ".yar") {
this->m_rules.push_back({ fs::relative(entry.path(), fs::path(path)).string(), entry.path().string() }); this->m_rules.push_back({ std::fs::relative(entry.path(), std::fs::path(path)).string(), entry.path().string() });
} }
} }
} }
@ -172,7 +172,7 @@ namespace hex::plugin::builtin {
[](const char *includeName, const char *callingRuleFileName, const char *callingRuleNamespace, void *userData) -> const char * { [](const char *includeName, const char *callingRuleFileName, const char *callingRuleNamespace, void *userData) -> const char * {
auto currFilePath = static_cast<const char *>(userData); auto currFilePath = static_cast<const char *>(userData);
File file((fs::path(currFilePath).parent_path() / includeName).string(), File::Mode::Read); fs::File file((std::fs::path(currFilePath).parent_path() / includeName).string(), fs::File::Mode::Read);
if (!file.isValid()) if (!file.isValid())
return nullptr; return nullptr;
@ -189,7 +189,7 @@ namespace hex::plugin::builtin {
this->m_rules[this->m_selectedRule].second.data()); this->m_rules[this->m_selectedRule].second.data());
File file(this->m_rules[this->m_selectedRule].second, File::Mode::Read); fs::File file(this->m_rules[this->m_selectedRule].second, fs::File::Mode::Read);
if (!file.isValid()) return; if (!file.isValid()) return;
if (yr_compiler_add_file(compiler, file.getHandle(), nullptr, nullptr) != 0) { if (yr_compiler_add_file(compiler, file.getHandle(), nullptr, nullptr) != 0) {

View File

@ -4,7 +4,7 @@
#include <hex/api/localization.hpp> #include <hex/api/localization.hpp>
#include <hex/api/plugin_manager.hpp> #include <hex/api/plugin_manager.hpp>
#include <hex/ui/view.hpp> #include <hex/ui/view.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
#include <hex/helpers/logger.hpp> #include <hex/helpers/logger.hpp>
@ -28,9 +28,9 @@ namespace hex::plugin::builtin {
static bool s_layoutConfigured = false; static bool s_layoutConfigured = false;
static ImGui::Texture s_bannerTexture; static ImGui::Texture s_bannerTexture;
static std::string s_bannerTextureName; static std::string s_bannerTextureName;
static std::list<fs::path> s_recentFilePaths; static std::list<std::fs::path> s_recentFilePaths;
static fs::path s_safetyBackupPath; static std::fs::path s_safetyBackupPath;
static std::string s_tipOfTheDay; static std::string s_tipOfTheDay;
@ -153,7 +153,7 @@ namespace hex::plugin::builtin {
ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 5_scaled); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 5_scaled);
{ {
for (auto &path : s_recentFilePaths) { for (auto &path : s_recentFilePaths) {
if (ImGui::BulletHyperlink(fs::path(path).filename().string().c_str())) { if (ImGui::BulletHyperlink(std::fs::path(path).filename().string().c_str())) {
EventManager::post<RequestOpenFile>(path); EventManager::post<RequestOpenFile>(path);
break; break;
} }
@ -384,7 +384,7 @@ namespace hex::plugin::builtin {
s_recentFilePaths.push_front(path); s_recentFilePaths.push_front(path);
{ {
std::list<fs::path> uniques; std::list<std::fs::path> uniques;
for (auto &file : s_recentFilePaths) { for (auto &file : s_recentFilePaths) {
bool exists = false; bool exists = false;
@ -420,16 +420,16 @@ namespace hex::plugin::builtin {
ContentRegistry::Interface::addMenuItem("hex.builtin.menu.file", 1050, [&] { ContentRegistry::Interface::addMenuItem("hex.builtin.menu.file", 1050, [&] {
if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.file.open_file"_lang, "CTRL + O")) { if (ImGui::MenuItem("hex.builtin.view.hex_editor.menu.file.open_file"_lang, "CTRL + O")) {
hex::openFileBrowser("hex.builtin.view.hex_editor.open_file"_lang, DialogMode::Open, {}, [](const auto &path) { fs::openFileBrowser("hex.builtin.view.hex_editor.open_file"_lang, fs::DialogMode::Open, {}, [](const auto &path) {
EventManager::post<RequestOpenFile>(path); EventManager::post<RequestOpenFile>(path);
}); });
} }
if (ImGui::BeginMenu("hex.builtin.view.hex_editor.menu.file.open_recent"_lang, !s_recentFilePaths.empty())) { if (ImGui::BeginMenu("hex.builtin.view.hex_editor.menu.file.open_recent"_lang, !s_recentFilePaths.empty())) {
// Copy to avoid chaning list while iteration // Copy to avoid changing list while iteration
std::list<fs::path> recentFilePaths = s_recentFilePaths; std::list<std::fs::path> recentFilePaths = s_recentFilePaths;
for (auto &path : recentFilePaths) { for (auto &path : recentFilePaths) {
auto filename = fs::path(path).filename().string(); auto filename = std::fs::path(path).filename().string();
if (ImGui::MenuItem(filename.c_str())) { if (ImGui::MenuItem(filename.c_str())) {
EventManager::post<RequestOpenFile>(path); EventManager::post<RequestOpenFile>(path);
} }
@ -461,8 +461,8 @@ namespace hex::plugin::builtin {
constexpr auto CrashBackupFileName = "crash_backup.hexproj"; constexpr auto CrashBackupFileName = "crash_backup.hexproj";
for (const auto &path : hex::getPath(ImHexPath::Config)) { for (const auto &path : fs::getDefaultPaths(fs::ImHexPath::Config)) {
if (auto filePath = fs::path(path) / CrashBackupFileName; fs::exists(filePath)) { if (auto filePath = std::fs::path(path) / CrashBackupFileName; fs::exists(filePath)) {
s_safetyBackupPath = filePath; s_safetyBackupPath = filePath;
ImHexApi::Tasks::doLater([] { ImGui::OpenPopup("hex.builtin.welcome.safety_backup.title"_lang); }); ImHexApi::Tasks::doLater([] { ImGui::OpenPopup("hex.builtin.welcome.safety_backup.title"_lang); });
} }

View File

@ -1,7 +1,7 @@
#include <hex/test/tests.hpp> #include <hex/test/tests.hpp>
#include <hex/helpers/file.hpp> #include <hex/helpers/file.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
using namespace std::literals::string_literals; using namespace std::literals::string_literals;

View File

@ -2,7 +2,7 @@
#include <hex/helpers/net.hpp> #include <hex/helpers/net.hpp>
#include <hex/helpers/file.hpp> #include <hex/helpers/file.hpp>
#include <hex/helpers/paths.hpp> #include <hex/helpers/fs.hpp>
using namespace std::literals::string_literals; using namespace std::literals::string_literals;