TAMSVIZ
Visualization and annotation tool for ROS
resource.h
1 // TAMSVIZ
2 // (c) 2020 Philipp Ruppel
3 
4 #pragma once
5 
6 #include "../core/event.h"
7 
8 #include <functional>
9 #include <map>
10 #include <memory>
11 #include <mutex>
12 #include <string>
13 #include <vector>
14 
15 void loadResource(const std::string &url, std::string &data);
16 void loadResource(const std::string &url, std::vector<uint8_t> &data);
17 
19  static ResourceEvents &instance();
20  Event<void()> reload{"reload"};
21 };
22 
23 class ResourceBase : public std::enable_shared_from_this<ResourceBase> {
24  bool _invalidate_connected = false;
25  EventFlag _invalidated{ResourceEvents::instance().reload};
26 
27 protected:
28  void cleanup(const std::function<void()> &callback);
29  bool invalidated() { _invalidated.poll(); }
30 
31 public:
32  static void setCleanupFunction(
33  const std::function<void(const std::function<void()> &)> &callback);
34  ResourceBase() {}
35  ResourceBase(const ResourceBase &) = delete;
36  ResourceBase &operator=(const ResourceBase &) = delete;
37 };
38 
39 template <class T, class... ARGS> class ResourceManager {
40  std::mutex _mutex;
41  std::map<std::tuple<ARGS...>, std::weak_ptr<T>> _map;
42 
43 public:
44  std::shared_ptr<T> load(const ARGS &... args) {
45  std::lock_guard<std::mutex> lock(_mutex);
46  auto &item = _map[std::make_tuple(args...)];
47  std::shared_ptr<T> ret = item.lock();
48  if (!ret) {
49  ret = std::make_shared<T>(args...);
50  }
51  item = ret;
52  return ret;
53  }
54  std::shared_ptr<T> fetchExisting(const ARGS &... args) {
55  std::lock_guard<std::mutex> lock(_mutex);
56  auto &item = _map[std::make_tuple(args...)];
57  return item.lock();
58  }
59  void clear() {
60  std::lock_guard<std::mutex> lock(_mutex);
61  _map.clear();
62  }
63 };