DataModel.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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-2023 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 "DataModel.h"
  29. #include "../../Include/RmlUi/Core/DataTypeRegister.h"
  30. #include "../../Include/RmlUi/Core/Element.h"
  31. #include "DataController.h"
  32. #include "DataView.h"
  33. namespace Rml {
  34. static DataAddress ParseAddress(const String& address_str)
  35. {
  36. StringList list;
  37. StringUtilities::ExpandString(list, address_str, '.');
  38. DataAddress address;
  39. address.reserve(list.size() * 2);
  40. for (const auto& item : list)
  41. {
  42. if (item.empty())
  43. return DataAddress();
  44. size_t i_open = item.find('[', 0);
  45. if (i_open == 0)
  46. return DataAddress();
  47. address.emplace_back(item.substr(0, i_open));
  48. while (i_open != String::npos)
  49. {
  50. size_t i_close = item.find(']', i_open + 1);
  51. if (i_close == String::npos)
  52. return DataAddress();
  53. int index = FromString<int>(item.substr(i_open + 1, i_close - i_open), -1);
  54. if (index < 0)
  55. return DataAddress();
  56. address.emplace_back(index);
  57. i_open = item.find('[', i_close + 1);
  58. }
  59. // TODO: Abort on invalid characters among [ ] and after the last found bracket?
  60. }
  61. RMLUI_ASSERT(!address.empty() && !address[0].name.empty());
  62. return address;
  63. }
  64. // Returns an error string on error, or nullptr on success.
  65. static const char* LegalVariableName(const String& name)
  66. {
  67. static SmallUnorderedSet<String> reserved_names{"it", "it_index", "ev", "true", "false", "size", "literal"};
  68. if (name.empty())
  69. return "Name cannot be empty.";
  70. const String name_lower = StringUtilities::ToLower(name);
  71. const char first = name_lower.front();
  72. if (!(first >= 'a' && first <= 'z'))
  73. return "First character must be 'a-z' or 'A-Z'.";
  74. for (const char c : name_lower)
  75. {
  76. if (!(c == '_' || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')))
  77. return "Name must strictly contain characters a-z, A-Z, 0-9 and under_score.";
  78. }
  79. if (reserved_names.count(name_lower) == 1)
  80. return "Name is reserved.";
  81. return nullptr;
  82. }
  83. static String DataAddressToString(const DataAddress& address)
  84. {
  85. String result;
  86. bool is_first = true;
  87. for (auto& entry : address)
  88. {
  89. if (entry.index >= 0)
  90. result += '[' + ToString(entry.index) + ']';
  91. else
  92. {
  93. if (!is_first)
  94. result += ".";
  95. result += entry.name;
  96. }
  97. is_first = false;
  98. }
  99. return result;
  100. }
  101. DataModel::DataModel(DataTypeRegister* data_type_register) : data_type_register(data_type_register)
  102. {
  103. views = MakeUnique<DataViews>();
  104. controllers = MakeUnique<DataControllers>();
  105. }
  106. DataModel::~DataModel()
  107. {
  108. RMLUI_ASSERT(attached_elements.empty());
  109. }
  110. void DataModel::AddView(DataViewPtr view)
  111. {
  112. views->Add(std::move(view));
  113. }
  114. void DataModel::AddController(DataControllerPtr controller)
  115. {
  116. controllers->Add(std::move(controller));
  117. }
  118. bool DataModel::BindVariable(const String& name, DataVariable variable)
  119. {
  120. const char* name_error_str = LegalVariableName(name);
  121. if (name_error_str)
  122. {
  123. Log::Message(Log::LT_WARNING, "Could not bind data variable '%s'. %s", name.c_str(), name_error_str);
  124. return false;
  125. }
  126. if (!variable)
  127. {
  128. Log::Message(Log::LT_WARNING, "Could not bind variable '%s' to data model, data type not registered.", name.c_str());
  129. return false;
  130. }
  131. bool inserted = variables.emplace(name, variable).second;
  132. if (!inserted)
  133. {
  134. Log::Message(Log::LT_WARNING, "Data model variable with name '%s' already exists.", name.c_str());
  135. return false;
  136. }
  137. return true;
  138. }
  139. bool DataModel::BindFunc(const String& name, DataGetFunc get_func, DataSetFunc set_func)
  140. {
  141. auto result = function_variable_definitions.emplace(name, nullptr);
  142. auto& it = result.first;
  143. bool inserted = result.second;
  144. if (!inserted)
  145. {
  146. Log::Message(Log::LT_ERROR, "Data get/set function with name %s already exists in model", name.c_str());
  147. return false;
  148. }
  149. auto& func_definition_ptr = it->second;
  150. func_definition_ptr = MakeUnique<FuncDefinition>(std::move(get_func), std::move(set_func));
  151. return BindVariable(name, DataVariable(func_definition_ptr.get(), nullptr));
  152. }
  153. bool DataModel::BindEventCallback(const String& name, DataEventFunc event_func)
  154. {
  155. const char* name_error_str = LegalVariableName(name);
  156. if (name_error_str)
  157. {
  158. Log::Message(Log::LT_WARNING, "Could not bind data event callback '%s'. %s", name.c_str(), name_error_str);
  159. return false;
  160. }
  161. if (!event_func)
  162. {
  163. Log::Message(Log::LT_WARNING, "Could not bind data event callback '%s' to data model, empty function provided.", name.c_str());
  164. return false;
  165. }
  166. bool inserted = event_callbacks.emplace(name, std::move(event_func)).second;
  167. if (!inserted)
  168. {
  169. Log::Message(Log::LT_WARNING, "Data event callback with name '%s' already exists.", name.c_str());
  170. return false;
  171. }
  172. return true;
  173. }
  174. bool DataModel::InsertAlias(Element* element, const String& alias_name, DataAddress replace_with_address)
  175. {
  176. if (replace_with_address.empty() || replace_with_address.front().name.empty())
  177. {
  178. Log::Message(Log::LT_WARNING, "Could not add alias variable '%s' to data model, replacement address invalid.", alias_name.c_str());
  179. return false;
  180. }
  181. if (variables.count(alias_name) == 1)
  182. Log::Message(Log::LT_WARNING, "Alias variable '%s' is shadowed by a global variable.", alias_name.c_str());
  183. auto& map = aliases.emplace(element, SmallUnorderedMap<String, DataAddress>()).first->second;
  184. auto it = map.find(alias_name);
  185. if (it != map.end())
  186. Log::Message(Log::LT_WARNING, "Alias name '%s' in data model already exists, replaced.", alias_name.c_str());
  187. map[alias_name] = std::move(replace_with_address);
  188. return true;
  189. }
  190. bool DataModel::EraseAliases(Element* element)
  191. {
  192. return aliases.erase(element) == 1;
  193. }
  194. void DataModel::CopyAliases(Element* from_element, Element* to_element)
  195. {
  196. if (from_element == to_element)
  197. return;
  198. auto existing_map = aliases.find(from_element);
  199. if (existing_map != aliases.end())
  200. {
  201. // Need to create a copy to prevent errors during concurrent modification for 3rd party containers
  202. auto copy = existing_map->second;
  203. for (auto const& it : copy)
  204. aliases[to_element][it.first] = std::move(it.second);
  205. }
  206. }
  207. DataAddress DataModel::ResolveAddress(const String& address_str, Element* element) const
  208. {
  209. DataAddress address = ParseAddress(address_str);
  210. if (address.empty())
  211. return address;
  212. const String& first_name = address.front().name;
  213. auto it = variables.find(first_name);
  214. if (it != variables.end())
  215. return address;
  216. // Look for a variable alias for the first name.
  217. Element* ancestor = element;
  218. while (ancestor && ancestor->GetDataModel() == this)
  219. {
  220. auto it_element = aliases.find(ancestor);
  221. if (it_element != aliases.end())
  222. {
  223. const auto& alias_names = it_element->second;
  224. auto it_alias_name = alias_names.find(first_name);
  225. if (it_alias_name != alias_names.end())
  226. {
  227. const DataAddress& replace_address = it_alias_name->second;
  228. if (replace_address.empty() || replace_address.front().name.empty())
  229. {
  230. // Variable alias is invalid
  231. return DataAddress();
  232. }
  233. // Insert the full alias address, replacing the first element.
  234. address[0] = replace_address[0];
  235. address.insert(address.begin() + 1, replace_address.begin() + 1, replace_address.end());
  236. return address;
  237. }
  238. }
  239. ancestor = ancestor->GetParentNode();
  240. }
  241. Log::Message(Log::LT_WARNING, "Could not find variable name '%s' in data model.", address_str.c_str());
  242. return DataAddress();
  243. }
  244. DataVariable DataModel::GetVariable(const DataAddress& address) const
  245. {
  246. if (address.empty())
  247. return DataVariable();
  248. auto it = variables.find(address.front().name);
  249. if (it != variables.end())
  250. {
  251. DataVariable variable = it->second;
  252. for (int i = 1; i < (int)address.size() && variable; i++)
  253. {
  254. variable = variable.Child(address[i]);
  255. if (!variable)
  256. return DataVariable();
  257. }
  258. return variable;
  259. }
  260. if (address[0].name == "literal")
  261. {
  262. if (address.size() > 2 && address[1].name == "int")
  263. return MakeLiteralIntVariable(address[2].index);
  264. }
  265. return DataVariable();
  266. }
  267. const DataEventFunc* DataModel::GetEventCallback(const String& name)
  268. {
  269. auto it = event_callbacks.find(name);
  270. if (it == event_callbacks.end())
  271. {
  272. Log::Message(Log::LT_WARNING, "Could not find data event callback '%s' in data model.", name.c_str());
  273. return nullptr;
  274. }
  275. return &it->second;
  276. }
  277. bool DataModel::GetVariableInto(const DataAddress& address, Variant& out_value) const
  278. {
  279. DataVariable variable = GetVariable(address);
  280. bool result = (variable && variable.Get(out_value));
  281. if (!result)
  282. Log::Message(Log::LT_WARNING, "Could not get value from data variable '%s'.", DataAddressToString(address).c_str());
  283. return result;
  284. }
  285. void DataModel::DirtyVariable(const String& variable_name)
  286. {
  287. RMLUI_ASSERTMSG(LegalVariableName(variable_name) == nullptr, "Illegal variable name provided. Only top-level variables can be dirtied.");
  288. RMLUI_ASSERTMSG(variables.count(variable_name) == 1, "In DirtyVariable: Variable name not found among added variables.");
  289. dirty_variables.emplace(variable_name);
  290. }
  291. bool DataModel::IsVariableDirty(const String& variable_name) const
  292. {
  293. RMLUI_ASSERTMSG(LegalVariableName(variable_name) == nullptr, "Illegal variable name provided. Only top-level variables can be dirtied.");
  294. return dirty_variables.count(variable_name) == 1;
  295. }
  296. void DataModel::DirtyAllVariables()
  297. {
  298. dirty_variables.reserve(variables.size());
  299. for (const auto& variable : variables)
  300. {
  301. dirty_variables.emplace(variable.first);
  302. }
  303. }
  304. bool DataModel::CallTransform(const String& name, const VariantList& arguments, Variant& out_result) const
  305. {
  306. if (const auto transform_register = data_type_register->GetTransformFuncRegister())
  307. return transform_register->Call(name, arguments, out_result);
  308. return false;
  309. }
  310. void DataModel::AttachModelRootElement(Element* element)
  311. {
  312. attached_elements.insert(element);
  313. }
  314. ElementList DataModel::GetAttachedModelRootElements() const
  315. {
  316. return ElementList(attached_elements.begin(), attached_elements.end());
  317. }
  318. void DataModel::OnElementRemove(Element* element)
  319. {
  320. EraseAliases(element);
  321. views->OnElementRemove(element);
  322. controllers->OnElementRemove(element);
  323. attached_elements.erase(element);
  324. }
  325. bool DataModel::Update(bool clear_dirty_variables)
  326. {
  327. const bool result = views->Update(*this, dirty_variables);
  328. if (clear_dirty_variables)
  329. dirty_variables.clear();
  330. return result;
  331. }
  332. } // namespace Rml