DataModel.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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 DataAddress ParseAddress(const String& address_str)
  33. {
  34. StringList list;
  35. StringUtilities::ExpandString(list, address_str, '.');
  36. DataAddress address;
  37. address.reserve(list.size() * 2);
  38. for (const auto& item : list)
  39. {
  40. if (item.empty())
  41. return DataAddress();
  42. size_t i_open = item.find('[', 0);
  43. if (i_open == 0)
  44. return DataAddress();
  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 DataAddress();
  51. int index = FromString<int>(item.substr(i_open + 1, i_close - i_open), -1);
  52. if (index < 0)
  53. return DataAddress();
  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. RMLUI_ASSERT(!address.empty() && !address[0].name.empty());
  60. return address;
  61. };
  62. // Returns an error string on error, or nullptr on success.
  63. static const char* LegalVariableName(const String& name)
  64. {
  65. static SmallUnorderedSet<String> reserved_names{ "it", "ev", "true", "false", "size" };
  66. if (name.empty())
  67. return "Name cannot be empty.";
  68. const String name_lower = StringUtilities::ToLower(name);
  69. const char first = name_lower.front();
  70. if (!(first >= 'a' && first <= 'z'))
  71. return "First character must be 'a-z' or 'A-Z'.";
  72. for (const char c : name_lower)
  73. {
  74. if (!(c == '_' || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')))
  75. return "Name must strictly contain characters a-z, A-Z, 0-9 and under_score.";
  76. }
  77. if (reserved_names.count(name_lower) == 1)
  78. return "Name is reserved.";
  79. return nullptr;
  80. }
  81. bool DataModel::BindVariable(const String& name, Variable variable)
  82. {
  83. const char* name_error_str = LegalVariableName(name);
  84. if (name_error_str)
  85. {
  86. Log::Message(Log::LT_WARNING, "Could not bind data variable '%s'. %s", name.c_str(), name_error_str);
  87. return false;
  88. }
  89. if (!variable)
  90. {
  91. Log::Message(Log::LT_WARNING, "Could not bind variable '%s' to data model, data type not registered.", name.c_str());
  92. return false;
  93. }
  94. bool inserted = variables.emplace(name, variable).second;
  95. if (!inserted)
  96. {
  97. Log::Message(Log::LT_WARNING, "Data model variable with name '%s' already exists.", name.c_str());
  98. return false;
  99. }
  100. return true;
  101. }
  102. bool DataModel::BindEventCallback(const String& name, DataEventFunc event_func)
  103. {
  104. const char* name_error_str = LegalVariableName(name);
  105. if (name_error_str)
  106. {
  107. Log::Message(Log::LT_WARNING, "Could not bind data event callback '%s'. %s", name.c_str(), name_error_str);
  108. return false;
  109. }
  110. if (!event_func)
  111. {
  112. Log::Message(Log::LT_WARNING, "Could not bind data event callback '%s' to data model, empty function provided.", name.c_str());
  113. return false;
  114. }
  115. bool inserted = event_callbacks.emplace(name, std::move(event_func)).second;
  116. if (!inserted)
  117. {
  118. Log::Message(Log::LT_WARNING, "Data event callback with name '%s' already exists.", name.c_str());
  119. return false;
  120. }
  121. return true;
  122. }
  123. bool DataModel::InsertAlias(Element* element, const String& alias_name, DataAddress replace_with_address)
  124. {
  125. if (replace_with_address.empty() || replace_with_address.front().name.empty())
  126. {
  127. Log::Message(Log::LT_WARNING, "Could not add alias variable '%s' to data model, replacement address invalid.", alias_name.c_str());
  128. return false;
  129. }
  130. if (variables.count(alias_name) == 1)
  131. Log::Message(Log::LT_WARNING, "Alias variable '%s' is shadowed by a global variable.", alias_name.c_str());
  132. auto& map = aliases.emplace(element, SmallUnorderedMap<String, DataAddress>()).first->second;
  133. auto it = map.find(alias_name);
  134. if (it != map.end())
  135. Log::Message(Log::LT_WARNING, "Alias name '%s' in data model already exists, replaced.", alias_name.c_str());
  136. map[alias_name] = std::move(replace_with_address);
  137. return true;
  138. }
  139. bool DataModel::EraseAliases(Element* element)
  140. {
  141. return aliases.erase(element) == 1;
  142. }
  143. DataAddress DataModel::ResolveAddress(const String& address_str, Element* element) const
  144. {
  145. DataAddress address = ParseAddress(address_str);
  146. if (address.empty())
  147. return address;
  148. const String& first_name = address.front().name;
  149. auto it = variables.find(first_name);
  150. if (it != variables.end())
  151. return address;
  152. // Look for a variable alias for the first name.
  153. Element* ancestor = element;
  154. while (ancestor && ancestor->GetDataModel() == this)
  155. {
  156. auto it_element = aliases.find(ancestor);
  157. if (it_element != aliases.end())
  158. {
  159. const auto& alias_names = it_element->second;
  160. auto it_alias_name = alias_names.find(first_name);
  161. if (it_alias_name != alias_names.end())
  162. {
  163. const DataAddress& replace_address = it_alias_name->second;
  164. if (replace_address.empty() || replace_address.front().name.empty())
  165. {
  166. // Variable alias is invalid
  167. return DataAddress();
  168. }
  169. // Insert the full alias address, replacing the first element.
  170. address[0] = replace_address[0];
  171. address.insert(address.begin() + 1, replace_address.begin() + 1, replace_address.end());
  172. return address;
  173. }
  174. }
  175. ancestor = ancestor->GetParentNode();
  176. }
  177. Log::Message(Log::LT_WARNING, "Could not find variable name '%s' in data model.", address_str.c_str());
  178. return DataAddress();
  179. }
  180. Variable DataModel::GetVariable(const DataAddress& address) const
  181. {
  182. if (address.empty() || address.front().name.empty())
  183. return Variable();
  184. auto it = variables.find(address.front().name);
  185. if (it == variables.end())
  186. return Variable();
  187. Variable variable = it->second;
  188. for (int i = 1; i < (int)address.size() && variable; i++)
  189. {
  190. variable = variable.GetChild(address[i]);
  191. if (!variable)
  192. return Variable();
  193. }
  194. return variable;
  195. }
  196. const DataEventFunc* DataModel::GetEventCallback(const String& name)
  197. {
  198. auto it = event_callbacks.find(name);
  199. if (it == event_callbacks.end())
  200. {
  201. Log::Message(Log::LT_WARNING, "Could not find data event callback '%s' in data model.", name.c_str());
  202. return nullptr;
  203. }
  204. return &it->second;
  205. }
  206. void DataModel::DirtyVariable(const String& variable_name)
  207. {
  208. RMLUI_ASSERTMSG(variables.count(variable_name) == 1, "Variable name not found among added variables.");
  209. dirty_variables.emplace(variable_name);
  210. }
  211. bool DataModel::IsVariableDirty(const String& variable_name) const
  212. {
  213. return dirty_variables.count(variable_name) == 1;
  214. }
  215. bool DataModel::CallTransform(const String& name, Variant& inout_result, const VariantList& arguments) const
  216. {
  217. if (transform_register)
  218. return transform_register->Call(name, inout_result, arguments);
  219. return false;
  220. }
  221. void DataModel::OnElementRemove(Element* element)
  222. {
  223. EraseAliases(element);
  224. views.OnElementRemove(element);
  225. controllers.OnElementRemove(element);
  226. }
  227. bool DataModel::Update()
  228. {
  229. bool result = views.Update(*this, dirty_variables);
  230. dirty_variables.clear();
  231. return result;
  232. }
  233. #ifdef RMLUI_DEBUG
  234. static struct TestDataVariables {
  235. TestDataVariables()
  236. {
  237. using IntVector = std::vector<int>;
  238. struct FunData {
  239. int i = 99;
  240. String x = "hello";
  241. IntVector magic = { 3, 5, 7, 11, 13 };
  242. };
  243. using FunArray = std::array<FunData, 3>;
  244. struct SmartData {
  245. bool valid = true;
  246. FunData fun;
  247. FunArray more_fun;
  248. };
  249. DataModel model;
  250. DataTypeRegister types;
  251. DataModelConstructor handle(&model, &types);
  252. {
  253. handle.RegisterArray<IntVector>();
  254. if (auto fun_handle = handle.RegisterStruct<FunData>())
  255. {
  256. fun_handle.AddMember("i", &FunData::i);
  257. fun_handle.AddMember("x", &FunData::x);
  258. fun_handle.AddMember("magic", &FunData::magic);
  259. }
  260. handle.RegisterArray<FunArray>();
  261. if (auto smart_handle = handle.RegisterStruct<SmartData>())
  262. {
  263. smart_handle.AddMember("valid", &SmartData::valid);
  264. smart_handle.AddMember("fun", &SmartData::fun);
  265. smart_handle.AddMember("more_fun", &SmartData::more_fun);
  266. }
  267. }
  268. SmartData data;
  269. data.fun.x = "Hello, we're in SmartData!";
  270. handle.Bind("data", &data);
  271. {
  272. std::vector<String> test_addresses = { "data.more_fun[1].magic[3]", "data.fun.x", "data.valid" };
  273. std::vector<String> expected_results = { ToString(data.more_fun[1].magic[3]), ToString(data.fun.x), ToString(data.valid) };
  274. std::vector<String> results;
  275. for (auto& str_address : test_addresses)
  276. {
  277. DataAddress address = ParseAddress(str_address);
  278. String result;
  279. if(model.GetValue<String>(address, result))
  280. results.push_back(result);
  281. }
  282. RMLUI_ASSERT(results == expected_results);
  283. bool success = model.GetVariable(ParseAddress("data.more_fun[1].magic[1]")).Set(Variant(String("199")));
  284. RMLUI_ASSERT(success && data.more_fun[1].magic[1] == 199);
  285. data.fun.magic = { 99, 190, 55, 2000, 50, 60, 70, 80, 90 };
  286. Variant test_get_result;
  287. bool test_get_success = model.GetVariable(ParseAddress("data.fun.magic[8]")).Get(test_get_result);
  288. RMLUI_ASSERT(test_get_success && test_get_result.Get<String>() == "90");
  289. }
  290. }
  291. } test_data_variables;
  292. #endif
  293. }
  294. }