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