Watcher.hh 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #ifndef WATCHER_H
  2. #define WATCHER_H
  3. #include <condition_variable>
  4. #include <unordered_set>
  5. #include <set>
  6. #include <node_api.h>
  7. #include "Glob.hh"
  8. #include "Event.hh"
  9. #include "Debounce.hh"
  10. #include "DirTree.hh"
  11. #include "Signal.hh"
  12. using namespace Napi;
  13. struct Watcher;
  14. using WatcherRef = std::shared_ptr<Watcher>;
  15. struct Callback {
  16. Napi::ThreadSafeFunction tsfn;
  17. Napi::FunctionReference ref;
  18. std::thread::id threadId;
  19. };
  20. class WatcherState {
  21. public:
  22. virtual ~WatcherState() = default;
  23. };
  24. struct Watcher {
  25. std::string mDir;
  26. std::unordered_set<std::string> mIgnorePaths;
  27. std::unordered_set<Glob> mIgnoreGlobs;
  28. EventList mEvents;
  29. std::shared_ptr<WatcherState> state;
  30. Watcher(std::string dir, std::unordered_set<std::string> ignorePaths, std::unordered_set<Glob> ignoreGlobs);
  31. ~Watcher();
  32. bool operator==(const Watcher &other) const {
  33. return mDir == other.mDir && mIgnorePaths == other.mIgnorePaths && mIgnoreGlobs == other.mIgnoreGlobs;
  34. }
  35. void wait();
  36. void notify();
  37. void notifyError(std::exception &err);
  38. bool watch(Function callback);
  39. bool unwatch(Function callback);
  40. void unref();
  41. bool isIgnored(std::string path);
  42. void destroy();
  43. static WatcherRef getShared(std::string dir, std::unordered_set<std::string> ignorePaths, std::unordered_set<Glob> ignoreGlobs);
  44. private:
  45. std::mutex mMutex;
  46. std::condition_variable mCond;
  47. std::vector<Callback> mCallbacks;
  48. std::shared_ptr<Debounce> mDebounce;
  49. std::vector<Callback>::iterator findCallback(Function callback);
  50. void clearCallbacks();
  51. void triggerCallbacks();
  52. };
  53. class WatcherError : public std::runtime_error {
  54. public:
  55. WatcherRef mWatcher;
  56. WatcherError(std::string msg, WatcherRef watcher) : std::runtime_error(msg), mWatcher(watcher) {}
  57. WatcherError(const char *msg, WatcherRef watcher) : std::runtime_error(msg), mWatcher(watcher) {}
  58. };
  59. #endif