SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
FileWatcher.cpp
Go to the documentation of this file.
2#include <Core/Logger.hpp>
3#include <Core/OSDef.hpp>
4
5#if defined(PLATFORM_LINUX)
6#include <sys/inotify.h>
7#include <unistd.h>
8
9#include <cerrno>
10#include <cstring>
11#include <unordered_map>
12#elif defined(PLATFORM_WIN)
13#define WIN32_LEAN_AND_MEAN
14#ifndef NOMINMAX
15#define NOMINMAX
16#endif
17#include <windows.h>
18#endif
19
20namespace Sleak {
21
22namespace {
23constexpr size_t EVENT_BUFFER_SIZE = 4096;
24}
25
26#if defined(PLATFORM_LINUX)
27
28struct FileWatcher::Impl {
29 int fd = -1;
30 std::unordered_map<int, std::string> dirs;
31};
32
33FileWatcher::FileWatcher() : m_impl(std::make_unique<Impl>()) {
34 m_impl->fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
35 if (m_impl->fd < 0)
36 SLEAK_ERROR("FileWatcher: inotify_init1 failed: {}",
37 std::strerror(errno));
38}
39
40FileWatcher::~FileWatcher() {
41 if (m_impl->fd >= 0) close(m_impl->fd);
42}
43
44bool FileWatcher::AddDirectory(const std::string& dir) {
45 if (m_impl->fd < 0) return false;
46 const int wd = inotify_add_watch(m_impl->fd, dir.c_str(),
47 IN_CLOSE_WRITE | IN_MOVED_TO);
48 if (wd < 0) {
49 SLEAK_ERROR("FileWatcher: can't watch {}: {}", dir,
50 std::strerror(errno));
51 return false;
52 }
53 m_impl->dirs[wd] = dir;
54 return true;
55}
56
57void FileWatcher::Poll(std::vector<std::string>& outChanged) {
58 if (m_impl->fd < 0) return;
59 alignas(inotify_event) char buf[EVENT_BUFFER_SIZE];
60 for (;;) {
61 const ssize_t len = read(m_impl->fd, buf, sizeof(buf));
62 if (len <= 0) break;
63 for (char* p = buf; p < buf + len;) {
64 const auto* ev = reinterpret_cast<const inotify_event*>(p);
65 p += sizeof(inotify_event) + ev->len;
66 if (ev->len == 0) continue;
67 const auto dir = m_impl->dirs.find(ev->wd);
68 if (dir == m_impl->dirs.end()) continue;
69 outChanged.push_back(dir->second + "/" + ev->name);
70 }
71 }
72}
73
74#elif defined(PLATFORM_WIN)
75
76namespace {
77constexpr DWORD WATCH_FILTER =
78 FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_FILE_NAME;
79
80struct WatchedDirectory {
81 std::string path;
82 HANDLE handle = INVALID_HANDLE_VALUE;
83 OVERLAPPED overlapped = {};
84 alignas(DWORD) char buffer[EVENT_BUFFER_SIZE];
85};
86
87/// Queues the next asynchronous change read for a directory.
88bool Arm(WatchedDirectory& dir) {
89 ResetEvent(dir.overlapped.hEvent);
90 return ReadDirectoryChangesW(dir.handle, dir.buffer, sizeof(dir.buffer),
91 FALSE, WATCH_FILTER, nullptr, &dir.overlapped,
92 nullptr) != 0;
93}
94
95/// Converts a counted UTF-16 file name to UTF-8.
96std::string ToUtf8(const WCHAR* name, int length) {
97 const int size = WideCharToMultiByte(CP_UTF8, 0, name, length, nullptr, 0,
98 nullptr, nullptr);
99 std::string out(size, '\0');
100 WideCharToMultiByte(CP_UTF8, 0, name, length, out.data(), size, nullptr,
101 nullptr);
102 return out;
103}
104} // namespace
105
106struct FileWatcher::Impl {
107 std::vector<std::unique_ptr<WatchedDirectory> > dirs;
108};
109
110FileWatcher::FileWatcher() : m_impl(std::make_unique<Impl>()) {}
111
112FileWatcher::~FileWatcher() {
113 for (auto& dir : m_impl->dirs) {
114 DWORD bytes = 0;
115 CancelIoEx(dir->handle, &dir->overlapped);
116 GetOverlappedResult(dir->handle, &dir->overlapped, &bytes, TRUE);
117 CloseHandle(dir->overlapped.hEvent);
118 CloseHandle(dir->handle);
119 }
120}
121
122bool FileWatcher::AddDirectory(const std::string& dir) {
123 auto watched = std::make_unique<WatchedDirectory>();
124 watched->path = dir;
125 watched->handle =
126 CreateFileA(dir.c_str(), FILE_LIST_DIRECTORY,
127 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
128 nullptr, OPEN_EXISTING,
129 FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, nullptr);
130 if (watched->handle == INVALID_HANDLE_VALUE) {
131 SLEAK_ERROR("FileWatcher: can't open {} (error {})", dir,
132 GetLastError());
133 return false;
134 }
135 watched->overlapped.hEvent = CreateEventA(nullptr, TRUE, FALSE, nullptr);
136 if (!watched->overlapped.hEvent || !Arm(*watched)) {
137 SLEAK_ERROR("FileWatcher: can't watch {} (error {})", dir,
138 GetLastError());
139 if (watched->overlapped.hEvent) CloseHandle(watched->overlapped.hEvent);
140 CloseHandle(watched->handle);
141 return false;
142 }
143 m_impl->dirs.push_back(std::move(watched));
144 return true;
145}
146
147void FileWatcher::Poll(std::vector<std::string>& outChanged) {
148 for (auto& dir : m_impl->dirs) {
149 DWORD bytes = 0;
150 if (!GetOverlappedResult(dir->handle, &dir->overlapped, &bytes, FALSE))
151 continue;
152 for (DWORD offset = 0; bytes > 0;) {
153 const auto* info = reinterpret_cast<const FILE_NOTIFY_INFORMATION*>(
154 dir->buffer + offset);
155 if (info->Action != FILE_ACTION_REMOVED &&
156 info->Action != FILE_ACTION_RENAMED_OLD_NAME) {
157 const int length =
158 static_cast<int>(info->FileNameLength / sizeof(WCHAR));
159 outChanged.push_back(dir->path + "/" +
160 ToUtf8(info->FileName, length));
161 }
162 if (info->NextEntryOffset == 0) break;
163 offset += info->NextEntryOffset;
164 }
165 Arm(*dir);
166 }
167}
168
169#else
170
172
173FileWatcher::FileWatcher() : m_impl(std::make_unique<Impl>()) {}
174
175FileWatcher::~FileWatcher() = default;
176
177bool FileWatcher::AddDirectory(const std::string& dir) {
178 SLEAK_WARN("FileWatcher: not supported on this platform ({})", dir);
179 return false;
180}
181
182void FileWatcher::Poll(std::vector<std::string>& outChanged) {
183 (void)outChanged;
184}
185
186#endif
187
188} // namespace Sleak
#define SLEAK_ERROR(...)
Definition Logger.hpp:22
#define SLEAK_WARN(...)
Definition Logger.hpp:21
void Poll(std::vector< std::string > &outChanged)
Appends full paths of files saved since the last call. Never blocks.
bool AddDirectory(const std::string &dir)
Starts watching a directory. Returns false if it can't be watched.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10