1 #pragma once
2 
3 #include <gtkmm.h>
4 
5 #include "json.hpp"
6 // for convenience
7 using json = nlohmann::json;
8 
9 class ConfigCache {
10 public:
ConfigCache()11     ConfigCache() {
12         auto cache_dir_path = Glib::build_filename(Glib::get_user_cache_dir(), Glib::get_prgname());
13         auto cache_dir = Gio::File::create_for_path(cache_dir_path);
14 
15         cache_file_path = Glib::build_filename(cache_dir_path, "cache.json");
16 
17         if (!cache_dir->query_exists()) {
18             cache_dir->make_directory_with_parents();
19         }
20 
21         refresh();
22     }
23 
refresh()24     void refresh() {
25         auto cache_file = Gio::File::create_for_path(cache_file_path);
26         if (!cache_file->query_exists()) {
27             cache_object = json{};
28             return;
29         }
30 
31         char* contents = nullptr;
32         gsize length = 0;
33         if (!cache_file->load_contents(contents, length)) {
34             throw std::runtime_error("Error loading cache file");
35         }
36 
37         cache_object = json::parse(contents);
38         g_free(contents);
39     }
40 
save()41     void save() {
42         auto cache_file = Gio::File::create_for_path(cache_file_path);
43         const auto cache_dump = cache_object.dump();
44         std::string empty;
45         cache_file->replace_contents(
46             cache_dump.c_str(), cache_dump.size(), empty, empty, false, Gio::FILE_CREATE_PRIVATE);
47     }
48 
49     json& operator[](std::string key) {
50         return cache_object[key];
51     }
52 
find(std::string key)53     json::iterator find(std::string key) {
54         return cache_object.find(key);
55     }
56 
begin()57     json::iterator begin() {
58         return cache_object.begin();
59     }
60 
end()61     json::iterator end() {
62         return cache_object.end();
63     }
64 
65 private:
66     json cache_object;
67     std::string cache_file_path;
68 };
69