DataModel.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. bool DataModel::Bind(const String& name, void* ptr, VariableDefinition* variable)
  62. {
  63. if (!variable)
  64. {
  65. Log::Message(Log::LT_WARNING, "No registered type could be found for the data variable '%s'.", name.c_str());
  66. return false;
  67. }
  68. RMLUI_ASSERT(ptr || variable->Type() == VariableType::Function);
  69. bool inserted = variables.emplace(name, Variable(variable, ptr)).second;
  70. if (!inserted)
  71. {
  72. Log::Message(Log::LT_WARNING, "Data model variable with name '%s' already exists.", name.c_str());
  73. return false;
  74. }
  75. return true;
  76. }
  77. Variable DataModel::GetVariable(const String& address_str) const
  78. {
  79. Address address = ParseAddress(address_str);
  80. if (address.empty() || address.front().name.empty())
  81. {
  82. Log::Message(Log::LT_WARNING, "Invalid data address '%s'.", address_str.c_str());
  83. return Variable();
  84. }
  85. Variable instance = GetVariable(address);
  86. if (!instance)
  87. {
  88. Log::Message(Log::LT_WARNING, "Could not find the data variable '%s'.", address_str.c_str());
  89. return Variable();
  90. }
  91. return instance;
  92. }
  93. Variable DataModel::GetVariable(const Address& address) const
  94. {
  95. if (address.empty() || address.front().name.empty())
  96. return Variable();
  97. auto it = variables.find(address.front().name);
  98. if (it == variables.end())
  99. return Variable();
  100. Variable variable = it->second;
  101. for (int i = 1; i < (int)address.size() && variable; i++)
  102. {
  103. variable = variable.GetChild(address[i]);
  104. if (!variable)
  105. return Variable();
  106. }
  107. return variable;
  108. }
  109. void DataModel::DirtyVariable(const String& variable_name)
  110. {
  111. RMLUI_ASSERTMSG(variables.count(variable_name) == 1, "Variable name not found among added variables.");
  112. dirty_variables.insert(variable_name);
  113. }
  114. bool DataModel::UpdateVariable(const String& variable_name)
  115. {
  116. auto it = dirty_variables.find(variable_name);
  117. if (it == dirty_variables.end())
  118. return false;
  119. SmallUnorderedSet< String > dirty_variable{ *it };
  120. dirty_variables.erase(it);
  121. bool result = views.Update(*this, dirty_variable);
  122. return result;
  123. }
  124. Address DataModel::ResolveAddress(const String& address_str, Element* parent) const
  125. {
  126. Address address = ParseAddress(address_str);
  127. if (address.empty() || address.front().name.empty())
  128. return Address();
  129. const String& first_name = address.front().name;
  130. auto it = variables.find(first_name);
  131. if (it != variables.end())
  132. return address;
  133. // Look for a variable alias for the first name.
  134. Element* ancestor = parent;
  135. while (ancestor && ancestor->GetDataModel() == this)
  136. {
  137. auto it_element = aliases.find(ancestor);
  138. if (it_element != aliases.end())
  139. {
  140. auto& alias_names = it_element->second;
  141. auto it_alias_name = alias_names.find(first_name);
  142. if (it_alias_name != alias_names.end())
  143. {
  144. const Address& replace_address = it_alias_name->second;
  145. if (replace_address.empty() || replace_address.front().name.empty())
  146. {
  147. // Variable alias is invalid
  148. return Address();
  149. }
  150. // Insert the full alias address, replacing the first element.
  151. address[0] = std::move(replace_address[0]);
  152. address.insert(address.begin() + 1, replace_address.begin() + 1, replace_address.end());
  153. return address;
  154. }
  155. }
  156. ancestor = ancestor->GetParentNode();
  157. }
  158. Log::Message(Log::LT_WARNING, "Could not find variable name '%s' in data model.", address_str.c_str());
  159. return Address();
  160. }
  161. bool DataModel::InsertAlias(Element* element, const String& alias_name, Address replace_with_address) const
  162. {
  163. if (replace_with_address.empty() || replace_with_address.front().name.empty())
  164. {
  165. Log::Message(Log::LT_WARNING, "Could not add alias variable '%s' to data model, replacement address invalid.", alias_name.c_str());
  166. return false;
  167. }
  168. auto& map = aliases.emplace(element, SmallUnorderedMap<String, Address>()).first->second;
  169. auto it = map.find(alias_name);
  170. if (it != map.end())
  171. Log::Message(Log::LT_WARNING, "Alias name '%s' in data model already exists, replaced.", alias_name.c_str());
  172. map[alias_name] = std::move(replace_with_address);
  173. return true;
  174. }
  175. bool DataModel::EraseAliases(Element* element) const
  176. {
  177. return aliases.erase(element) == 1;
  178. }
  179. bool DataModel::UpdateViews()
  180. {
  181. bool result = views.Update(*this, dirty_variables);
  182. dirty_variables.clear();
  183. return result;
  184. }
  185. void DataModel::OnElementRemove(Element* element)
  186. {
  187. EraseAliases(element);
  188. views.OnElementRemove(element);
  189. }
  190. #ifdef RMLUI_DEBUG
  191. static struct TestDataVariables {
  192. TestDataVariables()
  193. {
  194. using IntVector = std::vector<int>;
  195. struct FunData {
  196. int i = 99;
  197. String x = "hello";
  198. IntVector magic = { 3, 5, 7, 11, 13 };
  199. };
  200. using FunArray = std::array<FunData, 3>;
  201. struct SmartData {
  202. bool valid = true;
  203. FunData fun;
  204. FunArray more_fun;
  205. };
  206. DataModel model;
  207. DataTypeRegister types;
  208. DataModelHandle handle(&model, &types);
  209. {
  210. handle.RegisterArray<IntVector>();
  211. if (auto fun_handle = handle.RegisterStruct<FunData>())
  212. {
  213. fun_handle.AddMember("i", &FunData::i);
  214. fun_handle.AddMember("x", &FunData::x);
  215. fun_handle.AddMember("magic", &FunData::magic);
  216. }
  217. handle.RegisterArray<FunArray>();
  218. if (auto smart_handle = handle.RegisterStruct<SmartData>())
  219. {
  220. smart_handle.AddMember("valid", &SmartData::valid);
  221. smart_handle.AddMember("fun", &SmartData::fun);
  222. smart_handle.AddMember("more_fun", &SmartData::more_fun);
  223. }
  224. }
  225. SmartData data;
  226. data.fun.x = "Hello, we're in SmartData!";
  227. handle.Bind("data", &data);
  228. {
  229. std::vector<String> test_addresses = { "data.more_fun[1].magic[3]", "data.fun.x", "data.valid" };
  230. std::vector<String> expected_results = { ToString(data.more_fun[1].magic[3]), ToString(data.fun.x), ToString(data.valid) };
  231. std::vector<String> results;
  232. for (auto& str_address : test_addresses)
  233. {
  234. Address address = ParseAddress(str_address);
  235. String result;
  236. if(model.GetValue<String>(address, result))
  237. results.push_back(result);
  238. }
  239. RMLUI_ASSERT(results == expected_results);
  240. bool success = model.GetVariable("data.more_fun[1].magic[1]").Set(Variant(String("199")));
  241. RMLUI_ASSERT(success && data.more_fun[1].magic[1] == 199);
  242. data.fun.magic = { 99, 190, 55, 2000, 50, 60, 70, 80, 90 };
  243. Variant test_get_result;
  244. bool test_get_success = model.GetVariable("data.fun.magic[8]").Get(test_get_result);
  245. RMLUI_ASSERT(test_get_success && test_get_result.Get<String>() == "90");
  246. }
  247. }
  248. } test_data_variables;
  249. #endif
  250. }
  251. }