blob: 2ddb4a901e0d12f932d25296b6dd2dfc05ee8069 (
plain)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
#pragma once
#include "Base.h"
#include "cru/base/Base.h"
#include "cru/base/Format.h"
#include "cru/xml/XmlNode.h"
#include "mapper/MapperRegistry.h"
#include "style/StyleRuleSet.h"
#include <any>
#include <filesystem>
#include <typeindex>
#include <typeinfo>
namespace cru::ui {
class CRU_UI_API ThemeResourceKeyNotExistException : public Exception {
public:
using Exception::Exception;
};
class CRU_UI_API BadThemeResourceException : public Exception {
public:
using Exception::Exception;
};
class CRU_UI_API ThemeResourceDictionary : public Object {
CRU_DEFINE_CLASS_LOG_TAG("ThemeResources");
public:
static std::unique_ptr<ThemeResourceDictionary> FromFile(
const String& file_path);
static std::unique_ptr<ThemeResourceDictionary> FromFile(
std::filesystem::path file_path) {
return FromFile(String::FromStdPath(file_path));
}
explicit ThemeResourceDictionary(xml::XmlElementNode* xml_root,
bool clone = true);
CRU_DELETE_COPY(ThemeResourceDictionary)
CRU_DELETE_MOVE(ThemeResourceDictionary)
~ThemeResourceDictionary() override;
public:
template <typename T>
T GetResource(const String& key) {
auto find_result = resource_map_.find(key);
if (find_result == resource_map_.cend()) {
throw ThemeResourceKeyNotExistException(
Format(u"Theme resource key {} not exist.", key));
}
auto& cache = find_result->second.cache;
auto cache_find_result = cache.find(typeid(T));
if (cache_find_result != cache.cend()) {
return std::any_cast<T>(cache_find_result->second);
}
auto mapper_registry = mapper::MapperRegistry::GetInstance();
auto mapper = mapper_registry->GetMapper<T>();
auto resource = mapper->MapFromXml(find_result->second.xml_node);
cache[typeid(T)] = resource;
return resource;
}
private:
void UpdateResourceMap(xml::XmlElementNode* root_xml);
private:
struct ResourceEntry {
CRU_DEFAULT_CONSTRUCTOR_DESTRUCTOR(ResourceEntry)
CRU_DEFAULT_COPY(ResourceEntry)
CRU_DEFAULT_MOVE(ResourceEntry)
String name;
xml::XmlElementNode* xml_node;
std::unordered_map<std::type_index, std::any> cache;
};
std::unique_ptr<xml::XmlElementNode> xml_root_;
std::unordered_map<String, ResourceEntry> resource_map_;
};
} // namespace cru::ui
|