| 1 | // Copyright 2025 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "Common/FilesystemWatcher.h" |
| 5 | |
| 6 | #include <wtr/watcher.hpp> |
| 7 | |
| 8 | #include "Common/Logging/Log.h" |
| 9 | #include "Common/StringUtil.h" |
| 10 | |
| 11 | namespace Common |
| 12 | { |
| 13 | FilesystemWatcher::FilesystemWatcher() = default; |
| 14 | FilesystemWatcher::~FilesystemWatcher() = default; |
| 15 | |
| 16 | void FilesystemWatcher::Watch(const std::string& path) |
| 17 | { |
| 18 | const auto [iter, inserted] = m_watched_paths.try_emplace(path, nullptr); |
| 19 | if (inserted) |
| 20 | { |
| 21 | iter->second = std::make_unique<wtr::watch>(path, [this](wtr::event e) { |
| 22 | const auto watched_path = PathToString(e.path_name); |
| 23 | if (e.path_type == wtr::event::path_type::watcher) |
| 24 | { |
| 25 | if (watched_path.starts_with('e')) |
| 26 | ERROR_LOG_FMT(COMMON, "Filesystem watcher: '{}'", watched_path); |
| 27 | else if (watched_path.starts_with('w')) |
| 28 | WARN_LOG_FMT(COMMON, "Filesystem watcher: '{}'", watched_path); |
| 29 | return; |
| 30 | } |
| 31 | |
| 32 | if (e.effect_type == wtr::event::effect_type::create) |
| 33 | { |
| 34 | const auto unified_path = WithUnifiedPathSeparators(watched_path); |
| 35 | PathAdded(unified_path); |
| 36 | } |
| 37 | else if (e.effect_type == wtr::event::effect_type::modify) |
| 38 | { |
| 39 | const auto unified_path = WithUnifiedPathSeparators(watched_path); |
| 40 | PathModified(unified_path); |
| 41 | } |
| 42 | else if (e.effect_type == wtr::event::effect_type::rename) |
| 43 | { |
| 44 | if (!e.associated) |
| 45 | { |
| 46 | WARN_LOG_FMT(COMMON, "Rename on path '{}' seen without association!", watched_path); |
| 47 | return; |
| 48 | } |
| 49 | |
| 50 | const auto old_path = WithUnifiedPathSeparators(watched_path); |
| 51 | const auto new_path = WithUnifiedPathSeparators(PathToString(e.associated->path_name)); |
| 52 | PathRenamed(old_path, new_path); |
| 53 | } |
| 54 | else if (e.effect_type == wtr::event::effect_type::destroy) |
| 55 | { |
| 56 | const auto unified_path = WithUnifiedPathSeparators(watched_path); |
| 57 | PathDeleted(unified_path); |
| 58 | } |
| 59 | }); |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | void FilesystemWatcher::Unwatch(const std::string& path) |
| 64 | { |
| 65 | m_watched_paths.erase(path); |
| 66 | } |
| 67 | } // namespace Common |