DataModel.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "precompiled.h"
  29. #include "../../Include/RmlUi/Core/DataModel.h"
  30. namespace Rml {
  31. namespace Core {
  32. static Address ParseAddress(const String& address_str)
  33. {
  34. StringList list;
  35. StringUtilities::ExpandString(list, address_str, '.');
  36. Address address;
  37. address.reserve(list.size() * 2);
  38. for (const auto& item : list)
  39. {
  40. if (item.empty())
  41. return Address();
  42. size_t i_open = item.find('[', 0);
  43. if (i_open == 0)
  44. return Address();
  45. address.emplace_back(item.substr(0, i_open));
  46. while (i_open != String::npos)
  47. {
  48. size_t i_close = item.find(']', i_open + 1);
  49. if (i_close == String::npos)
  50. return Address();
  51. int index = FromString<int>(item.substr(i_open + 1, i_close - i_open), -1);
  52. if (index < 0)
  53. return Address();
  54. address.emplace_back(index);
  55. i_open = item.find('[', i_close + 1);
  56. }
  57. // TODO: Abort on invalid characters among [ ] and after the last found bracket?
  58. }
  59. return address;
  60. };
  61. Variant DataModel::GetValue(const Rml::Core::String& address_str) const
  62. {
  63. Variable variable = GetVariable(address_str);
  64. Variant result;
  65. if (!variable)
  66. return result;
  67. if (variable.Type() != VariableType::Scalar)
  68. {
  69. Log::Message(Log::LT_WARNING, "Error retrieving data variable '%s': Only the values of scalar variables can be parsed.", address_str.c_str());
  70. return result;
  71. }
  72. if (!variable.Get(result))
  73. Log::Message(Log::LT_WARNING, "Could not parse data value '%s'", address_str.c_str());
  74. return result;
  75. }
  76. bool DataModel::SetValue(const String& address_str, const Variant& variant) const
  77. {
  78. Variable variable = GetVariable(address_str);
  79. if (!variable)
  80. return false;
  81. if (variable.Type() != VariableType::Scalar)
  82. {
  83. Log::Message(Log::LT_WARNING, "Could not assign data value '%s', variable is not a scalar type.", address_str.c_str());
  84. return false;
  85. }
  86. if (!variable.Set(variant))
  87. {
  88. Log::Message(Log::LT_WARNING, "Could not assign data value '%s'", address_str.c_str());
  89. return false;
  90. }
  91. return true;
  92. }
  93. bool DataModel::Bind(String name, void* ptr, VariableDefinition* variable, VariableType type)
  94. {
  95. RMLUI_ASSERT(ptr);
  96. if (!variable)
  97. {
  98. Log::Message(Log::LT_WARNING, "No registered type could be found for the data variable '%s'.", name.c_str());
  99. return false;
  100. }
  101. if (variable->Type() != type)
  102. {
  103. Log::Message(Log::LT_WARNING, "The registered type does not match the given type for the data variable '%s'.", name.c_str());
  104. return false;
  105. }
  106. bool inserted = variables.emplace(name, Variable(variable, ptr)).second;
  107. if (!inserted)
  108. {
  109. Log::Message(Log::LT_WARNING, "Data model variable with name '%s' already exists.", name.c_str());
  110. return false;
  111. }
  112. return true;
  113. }
  114. Variable DataModel::GetVariable(const String& address_str) const
  115. {
  116. Address address = ParseAddress(address_str);
  117. if (address.empty() || address.front().name.empty())
  118. {
  119. Log::Message(Log::LT_WARNING, "Invalid data address '%s'.", address_str.c_str());
  120. return Variable();
  121. }
  122. Variable instance = GetVariable(address);
  123. if (!instance)
  124. {
  125. Log::Message(Log::LT_WARNING, "Could not find the data variable '%s'.", address_str.c_str());
  126. return Variable();
  127. }
  128. return instance;
  129. }
  130. Variable DataModel::GetVariable(const Address& address) const
  131. {
  132. if (address.empty() || address.front().name.empty())
  133. return Variable();
  134. auto it = variables.find(address.front().name);
  135. if (it == variables.end())
  136. return Variable();
  137. Variable variable = it->second;
  138. for (int i = 1; i < (int)address.size() && variable; i++)
  139. {
  140. variable = variable.GetChild(address[i]);
  141. if (!variable)
  142. return Variable();
  143. }
  144. return variable;
  145. }
  146. Address DataModel::ResolveAddress(const String& address_str, Element* parent) const
  147. {
  148. Address address = ParseAddress(address_str);
  149. if (address.empty() || address.front().name.empty())
  150. return Address();
  151. const String& first_name = address.front().name;
  152. auto it = variables.find(first_name);
  153. if (it != variables.end())
  154. return address;
  155. // Look for a variable alias for the first name.
  156. Element* ancestor = parent;
  157. while (ancestor && ancestor->GetDataModel() == this)
  158. {
  159. auto it_element = aliases.find(ancestor);
  160. if (it_element != aliases.end())
  161. {
  162. auto& alias_names = it_element->second;
  163. auto it_alias_name = alias_names.find(first_name);
  164. if (it_alias_name != alias_names.end())
  165. {
  166. const Address& replace_address = it_alias_name->second;
  167. if (replace_address.empty() || replace_address.front().name.empty())
  168. {
  169. // Variable alias is invalid
  170. return Address();
  171. }
  172. // Insert the full alias address, replacing the first element.
  173. address[0] = std::move(replace_address[0]);
  174. address.insert(address.begin() + 1, replace_address.begin() + 1, replace_address.end());
  175. return address;
  176. }
  177. }
  178. ancestor = ancestor->GetParentNode();
  179. }
  180. Log::Message(Log::LT_WARNING, "Could not find variable name '%s' in data model.", address_str.c_str());
  181. return Address();
  182. }
  183. bool DataModel::InsertAlias(Element* element, const String& alias_name, Address replace_with_address) const
  184. {
  185. if (replace_with_address.empty() || replace_with_address.front().name.empty())
  186. {
  187. Log::Message(Log::LT_WARNING, "Could not add alias variable '%s' to data model, replacement address invalid.", alias_name.c_str());
  188. return false;
  189. }
  190. auto& map = aliases.emplace(element, SmallUnorderedMap<String, Address>()).first->second;
  191. auto it = map.find(alias_name);
  192. if(it != map.end())
  193. Log::Message(Log::LT_WARNING, "Alias name '%s' in data model already exists, replaced.", alias_name.c_str());
  194. map[alias_name] = std::move(replace_with_address);
  195. return true;
  196. }
  197. bool DataModel::EraseAliases(Element* element) const
  198. {
  199. return aliases.erase(element) == 1;
  200. }
  201. void DataModel::OnElementRemove(Element* element)
  202. {
  203. EraseAliases(element);
  204. views.OnElementRemove(element);
  205. }
  206. #ifdef RMLUI_DEBUG
  207. static struct TestDataVariables {
  208. TestDataVariables()
  209. {
  210. using IntVector = std::vector<int>;
  211. struct FunData {
  212. int i = 99;
  213. String x = "hello";
  214. IntVector magic = { 3, 5, 7, 11, 13 };
  215. };
  216. using FunArray = std::array<FunData, 3>;
  217. struct SmartData {
  218. bool valid = true;
  219. FunData fun;
  220. FunArray more_fun;
  221. };
  222. DataTypeRegister types;
  223. {
  224. auto int_vector_handle = types.RegisterArray<IntVector>();
  225. auto fun_handle = types.RegisterStruct<FunData>();
  226. if (fun_handle)
  227. {
  228. fun_handle.RegisterMember("i", &FunData::i);
  229. fun_handle.RegisterMember("x", &FunData::x);
  230. fun_handle.RegisterMember("magic", &FunData::magic, int_vector_handle);
  231. }
  232. auto fun_array_handle = types.RegisterArray<FunArray>(fun_handle);
  233. auto smart_handle = types.RegisterStruct<SmartData>();
  234. if (smart_handle)
  235. {
  236. smart_handle.RegisterMember("valid", &SmartData::valid);
  237. smart_handle.RegisterMember("fun", &SmartData::fun, fun_handle);
  238. smart_handle.RegisterMember("more_fun", &SmartData::more_fun, fun_array_handle);
  239. }
  240. }
  241. DataModel model(&types);
  242. SmartData data;
  243. data.fun.x = "Hello, we're in SmartData!";
  244. model.BindStruct("data", &data);
  245. {
  246. std::vector<String> test_addresses = { "data.more_fun[1].magic[3]", "data.fun.x", "data.valid" };
  247. std::vector<String> expected_results = { ToString(data.more_fun[1].magic[3]), ToString(data.fun.x), ToString(data.valid) };
  248. std::vector<String> results;
  249. for (auto& address : test_addresses)
  250. {
  251. auto the_address = ParseAddress(address);
  252. Variant variant = model.GetValue(address);
  253. results.push_back(variant.Get<String>());
  254. }
  255. RMLUI_ASSERT(results == expected_results);
  256. bool success = model.SetValue("data.more_fun[1].magic[1]", Variant(String("199")));
  257. RMLUI_ASSERT(success && data.more_fun[1].magic[1] == 199);
  258. data.fun.magic = { 99, 190, 55, 2000, 50, 60, 70, 80, 90 };
  259. String result = model.GetValue("data.fun.magic[8]").Get<String>();
  260. RMLUI_ASSERT(result == "90");
  261. }
  262. }
  263. } test_data_variables;
  264. #endif
  265. }
  266. }