2
0

DataModel.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 "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", "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) :
  102. data_type_register(data_type_register)
  103. {
  104. views = MakeUnique<DataViews>();
  105. controllers = MakeUnique<DataControllers>();
  106. }
  107. DataModel::~DataModel()
  108. {
  109. RMLUI_ASSERT(attached_elements.empty());
  110. }
  111. void DataModel::AddView(DataViewPtr view) {
  112. views->Add(std::move(view));
  113. }
  114. void DataModel::AddController(DataControllerPtr controller) {
  115. controllers->Add(std::move(controller));
  116. }
  117. bool DataModel::BindVariable(const String& name, DataVariable variable)
  118. {
  119. const char* name_error_str = LegalVariableName(name);
  120. if (name_error_str)
  121. {
  122. Log::Message(Log::LT_WARNING, "Could not bind data variable '%s'. %s", name.c_str(), name_error_str);
  123. return false;
  124. }
  125. if (!variable)
  126. {
  127. Log::Message(Log::LT_WARNING, "Could not bind variable '%s' to data model, data type not registered.", name.c_str());
  128. return false;
  129. }
  130. bool inserted = variables.emplace(name, variable).second;
  131. if (!inserted)
  132. {
  133. Log::Message(Log::LT_WARNING, "Data model variable with name '%s' already exists.", name.c_str());
  134. return false;
  135. }
  136. return true;
  137. }
  138. bool DataModel::BindFunc(const String& name, DataGetFunc get_func, DataSetFunc set_func)
  139. {
  140. auto result = function_variable_definitions.emplace(name, nullptr);
  141. auto& it = result.first;
  142. bool inserted = result.second;
  143. if (!inserted)
  144. {
  145. Log::Message(Log::LT_ERROR, "Data get/set function with name %s already exists in model", name.c_str());
  146. return false;
  147. }
  148. auto& func_definition_ptr = it->second;
  149. func_definition_ptr = MakeUnique<FuncDefinition>(std::move(get_func), std::move(set_func));
  150. return BindVariable(name, DataVariable(func_definition_ptr.get(), nullptr));
  151. }
  152. bool DataModel::BindEventCallback(const String& name, DataEventFunc event_func)
  153. {
  154. const char* name_error_str = LegalVariableName(name);
  155. if (name_error_str)
  156. {
  157. Log::Message(Log::LT_WARNING, "Could not bind data event callback '%s'. %s", name.c_str(), name_error_str);
  158. return false;
  159. }
  160. if (!event_func)
  161. {
  162. Log::Message(Log::LT_WARNING, "Could not bind data event callback '%s' to data model, empty function provided.", name.c_str());
  163. return false;
  164. }
  165. bool inserted = event_callbacks.emplace(name, std::move(event_func)).second;
  166. if (!inserted)
  167. {
  168. Log::Message(Log::LT_WARNING, "Data event callback with name '%s' already exists.", name.c_str());
  169. return false;
  170. }
  171. return true;
  172. }
  173. bool DataModel::InsertAlias(Element* element, const String& alias_name, DataAddress replace_with_address)
  174. {
  175. if (replace_with_address.empty() || replace_with_address.front().name.empty())
  176. {
  177. Log::Message(Log::LT_WARNING, "Could not add alias variable '%s' to data model, replacement address invalid.", alias_name.c_str());
  178. return false;
  179. }
  180. if (variables.count(alias_name) == 1)
  181. Log::Message(Log::LT_WARNING, "Alias variable '%s' is shadowed by a global variable.", alias_name.c_str());
  182. auto& map = aliases.emplace(element, SmallUnorderedMap<String, DataAddress>()).first->second;
  183. auto it = map.find(alias_name);
  184. if (it != map.end())
  185. Log::Message(Log::LT_WARNING, "Alias name '%s' in data model already exists, replaced.", alias_name.c_str());
  186. map[alias_name] = std::move(replace_with_address);
  187. return true;
  188. }
  189. bool DataModel::EraseAliases(Element* element)
  190. {
  191. return aliases.erase(element) == 1;
  192. }
  193. DataAddress DataModel::ResolveAddress(const String& address_str, Element* element) const
  194. {
  195. DataAddress address = ParseAddress(address_str);
  196. if (address.empty())
  197. return address;
  198. const String& first_name = address.front().name;
  199. auto it = variables.find(first_name);
  200. if (it != variables.end())
  201. return address;
  202. // Look for a variable alias for the first name.
  203. Element* ancestor = element;
  204. while (ancestor && ancestor->GetDataModel() == this)
  205. {
  206. auto it_element = aliases.find(ancestor);
  207. if (it_element != aliases.end())
  208. {
  209. const auto& alias_names = it_element->second;
  210. auto it_alias_name = alias_names.find(first_name);
  211. if (it_alias_name != alias_names.end())
  212. {
  213. const DataAddress& replace_address = it_alias_name->second;
  214. if (replace_address.empty() || replace_address.front().name.empty())
  215. {
  216. // Variable alias is invalid
  217. return DataAddress();
  218. }
  219. // Insert the full alias address, replacing the first element.
  220. address[0] = replace_address[0];
  221. address.insert(address.begin() + 1, replace_address.begin() + 1, replace_address.end());
  222. return address;
  223. }
  224. }
  225. ancestor = ancestor->GetParentNode();
  226. }
  227. Log::Message(Log::LT_WARNING, "Could not find variable name '%s' in data model.", address_str.c_str());
  228. return DataAddress();
  229. }
  230. DataVariable DataModel::GetVariable(const DataAddress& address) const
  231. {
  232. if (address.empty())
  233. return DataVariable();
  234. auto it = variables.find(address.front().name);
  235. if (it != variables.end())
  236. {
  237. DataVariable variable = it->second;
  238. for (int i = 1; i < (int)address.size() && variable; i++)
  239. {
  240. variable = variable.Child(address[i]);
  241. if (!variable)
  242. return DataVariable();
  243. }
  244. return variable;
  245. }
  246. if (address[0].name == "literal")
  247. {
  248. if (address.size() > 2 && address[1].name == "int")
  249. return MakeLiteralIntVariable(address[2].index);
  250. }
  251. return DataVariable();
  252. }
  253. const DataEventFunc* DataModel::GetEventCallback(const String& name)
  254. {
  255. auto it = event_callbacks.find(name);
  256. if (it == event_callbacks.end())
  257. {
  258. Log::Message(Log::LT_WARNING, "Could not find data event callback '%s' in data model.", name.c_str());
  259. return nullptr;
  260. }
  261. return &it->second;
  262. }
  263. bool DataModel::GetVariableInto(const DataAddress& address, Variant& out_value) const {
  264. DataVariable variable = GetVariable(address);
  265. bool result = (variable && variable.Get(out_value));
  266. if (!result)
  267. Log::Message(Log::LT_WARNING, "Could not get value from data variable '%s'.", DataAddressToString(address).c_str());
  268. return result;
  269. }
  270. void DataModel::DirtyVariable(const String& variable_name)
  271. {
  272. RMLUI_ASSERTMSG(LegalVariableName(variable_name) == nullptr, "Illegal variable name provided. Only top-level variables can be dirtied.");
  273. RMLUI_ASSERTMSG(variables.count(variable_name) == 1, "In DirtyVariable: Variable name not found among added variables.");
  274. dirty_variables.emplace(variable_name);
  275. }
  276. bool DataModel::IsVariableDirty(const String& variable_name) const
  277. {
  278. RMLUI_ASSERTMSG(LegalVariableName(variable_name) == nullptr, "Illegal variable name provided. Only top-level variables can be dirtied.");
  279. return dirty_variables.count(variable_name) == 1;
  280. }
  281. void DataModel::DirtyAllVariables() {
  282. dirty_variables.reserve(variables.size());
  283. for (const auto& variable : variables) {
  284. dirty_variables.emplace(variable.first);
  285. }
  286. }
  287. bool DataModel::CallTransform(const String& name, const VariantList& arguments, Variant& out_result) const
  288. {
  289. if (const auto transform_register = data_type_register->GetTransformFuncRegister())
  290. return transform_register->Call(name, arguments, out_result);
  291. return false;
  292. }
  293. void DataModel::AttachModelRootElement(Element* element)
  294. {
  295. attached_elements.insert(element);
  296. }
  297. ElementList DataModel::GetAttachedModelRootElements() const
  298. {
  299. return ElementList(attached_elements.begin(), attached_elements.end());
  300. }
  301. void DataModel::OnElementRemove(Element* element)
  302. {
  303. EraseAliases(element);
  304. views->OnElementRemove(element);
  305. controllers->OnElementRemove(element);
  306. attached_elements.erase(element);
  307. }
  308. bool DataModel::Update(bool clear_dirty_variables)
  309. {
  310. const bool result = views->Update(*this, dirty_variables);
  311. if (clear_dirty_variables)
  312. dirty_variables.clear();
  313. return result;
  314. }
  315. } // namespace Rml