forked from kidanger/vpv
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwatcher.cpp
More file actions
67 lines (55 loc) · 1.66 KB
/
watcher.cpp
File metadata and controls
67 lines (55 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <libgen.h>
#include <string.h>
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
#include "efsw/efsw.hpp"
#include "watcher.hpp"
static efsw::FileWatcher* fileWatcher;
static std::map<std::string, std::vector<void(*)(const std::string&)>> callbacks;
class UpdateListener : public efsw::FileWatchListener
{
public:
UpdateListener() {}
void handleFileAction( efsw::WatchID watchid, const std::string& dir, const std::string& filename, efsw::Action action, std::string oldFilename = "" )
{
// possibly the worse way of doing this
std::string possibles[] = {
filename,
dir + filename,
dir + "/" + filename,
"./" + filename,
"./" + dir + filename,
"./" + dir + "/" + filename,
};
for (auto fullpath : possibles) {
if (!callbacks[fullpath].empty()) {
for (auto& clb : callbacks[fullpath]) {
clb(fullpath);
}
}
}
}
};
static UpdateListener* listener;
void watcher_initialize(void)
{
fileWatcher = new efsw::FileWatcher();
listener = new UpdateListener();
fileWatcher->watch();
}
void watcher_add_file(const std::string& filename, void(*clb)(const std::string& filename))
{
if (!fileWatcher) return;
auto& vec = callbacks[filename];
if (std::find(vec.begin(), vec.end(), clb) != vec.end()) {
// we assumed it's already watched
return;
}
char* ddir = strdup(filename.c_str());
char* dir = dirname(ddir);
fileWatcher->addWatch(dir, listener, false);
callbacks[filename].push_back(clb);
free(ddir);
}