DataView.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. #include "../../Include/RmlUi/Core/DataView.h"
  31. #include "DataParser.h"
  32. namespace Rml {
  33. namespace Core {
  34. DataView::~DataView() {}
  35. Element* DataView::GetElement() const
  36. {
  37. Element* result = attached_element.get();
  38. if (!result)
  39. Log::Message(Log::LT_WARNING, "Could not retrieve element in view, was it destroyed?");
  40. return result;
  41. }
  42. DataView::DataView(Element* element) : attached_element(element->GetObserverPtr()), element_depth(0) {
  43. if (element)
  44. {
  45. for (Element* parent = element->GetParentNode(); parent; parent = parent->GetParentNode())
  46. element_depth += 1;
  47. }
  48. }
  49. DataViewText::DataViewText(DataModel& model, ElementText* parent_element, const String& in_text, const size_t index_begin_search) : DataView(parent_element)
  50. {
  51. text.reserve(in_text.size());
  52. DataVariableInterface variable_interface(&model, parent_element);
  53. bool success = true;
  54. size_t previous_close_brackets = 0;
  55. size_t begin_brackets = index_begin_search;
  56. while ((begin_brackets = in_text.find("{{", begin_brackets)) != String::npos)
  57. {
  58. text.insert(text.end(), in_text.begin() + previous_close_brackets, in_text.begin() + begin_brackets);
  59. const size_t begin_name = begin_brackets + 2;
  60. const size_t end_name = in_text.find("}}", begin_name);
  61. if (end_name == String::npos)
  62. {
  63. success = false;
  64. break;
  65. }
  66. DataEntry entry;
  67. entry.index = text.size();
  68. entry.data_expression = std::make_unique<DataExpression>(String(in_text.begin() + begin_name, in_text.begin() + end_name));
  69. if (entry.data_expression->Parse(variable_interface))
  70. data_entries.push_back(std::move(entry));
  71. previous_close_brackets = end_name + 2;
  72. begin_brackets = previous_close_brackets;
  73. }
  74. if (data_entries.empty())
  75. success = false;
  76. if (success && previous_close_brackets < in_text.size())
  77. text.insert(text.end(), in_text.begin() + previous_close_brackets, in_text.end());
  78. if (!success)
  79. {
  80. text.clear();
  81. data_entries.clear();
  82. InvalidateView();
  83. }
  84. }
  85. DataViewText::~DataViewText()
  86. {}
  87. bool DataViewText::Update(DataModel& model)
  88. {
  89. bool entries_modified = false;
  90. Element* element = GetElement();
  91. DataVariableInterface variable_interface(&model, element);
  92. for (DataEntry& entry : data_entries)
  93. {
  94. RMLUI_ASSERT(entry.data_expression);
  95. Variant variant;
  96. bool result = entry.data_expression->Run(variable_interface, variant);
  97. const String value = variant.Get<String>();
  98. if (result && entry.value != value)
  99. {
  100. entry.value = value;
  101. entries_modified = true;
  102. }
  103. }
  104. if (entries_modified)
  105. {
  106. if (Element* element = GetElement())
  107. {
  108. RMLUI_ASSERTMSG(rmlui_dynamic_cast<ElementText*>(element), "Somehow the element type was changed from ElementText since construction of the view. Should not be possible?");
  109. if(auto text_element = static_cast<ElementText*>(element))
  110. {
  111. String new_text = BuildText();
  112. text_element->SetText(new_text);
  113. }
  114. }
  115. else
  116. {
  117. Log::Message(Log::LT_WARNING, "Could not update data view text, element no longer valid. Was it destroyed?");
  118. }
  119. }
  120. return entries_modified;
  121. }
  122. StringList DataViewText::GetVariableNameList() const
  123. {
  124. StringList full_list;
  125. full_list.reserve(data_entries.size());
  126. for (const DataEntry& entry : data_entries)
  127. {
  128. RMLUI_ASSERT(entry.data_expression);
  129. StringList entry_list = entry.data_expression->GetVariableNameList();
  130. full_list.insert(full_list.end(),
  131. std::make_move_iterator(entry_list.begin()),
  132. std::make_move_iterator(entry_list.end())
  133. );
  134. }
  135. return full_list;
  136. }
  137. String DataViewText::BuildText() const
  138. {
  139. size_t reserve_size = text.size();
  140. for (const DataEntry& entry : data_entries)
  141. reserve_size += entry.value.size();
  142. String result;
  143. result.reserve(reserve_size);
  144. size_t previous_index = 0;
  145. for (const DataEntry& entry : data_entries)
  146. {
  147. result += text.substr(previous_index, entry.index - previous_index);
  148. result += entry.value;
  149. previous_index = entry.index;
  150. }
  151. if (previous_index < text.size())
  152. result += text.substr(previous_index);
  153. return result;
  154. }
  155. DataViewAttribute::DataViewAttribute(DataModel& model, Element* element, const String& binding_name, const String& attribute_name)
  156. : DataView(element), attribute_name(attribute_name)
  157. {
  158. data_expression = std::make_unique<DataExpression>(binding_name);
  159. DataVariableInterface interface(&model, element);
  160. if (!data_expression->Parse(interface))
  161. InvalidateView();
  162. }
  163. DataViewAttribute::~DataViewAttribute()
  164. {}
  165. bool DataViewAttribute::Update(DataModel& model)
  166. {
  167. bool result = false;
  168. Variant variant;
  169. Element* element = GetElement();
  170. DataVariableInterface interface(&model, element);
  171. if (element && data_expression->Run(interface, variant))
  172. {
  173. const String value = variant.Get<String>();
  174. const Variant* attribute = element->GetAttribute(attribute_name);
  175. if (!attribute || (attribute && attribute->Get<String>() != value))
  176. {
  177. element->SetAttribute(attribute_name, value);
  178. result = true;
  179. }
  180. }
  181. return result;
  182. }
  183. StringList DataViewAttribute::GetVariableNameList() const {
  184. return data_expression ? data_expression->GetVariableNameList() : StringList();
  185. }
  186. DataViewStyle::DataViewStyle(DataModel& model, Element* element, const String& binding_name, const String& property_name)
  187. : DataView(element), property_name(property_name)
  188. {
  189. data_expression = std::make_unique<DataExpression>(binding_name);
  190. DataVariableInterface interface(&model, element);
  191. if(!data_expression->Parse(interface))
  192. InvalidateView();
  193. }
  194. DataViewStyle::~DataViewStyle()
  195. {
  196. }
  197. bool DataViewStyle::Update(DataModel& model)
  198. {
  199. bool result = false;
  200. Variant variant;
  201. Element* element = GetElement();
  202. DataVariableInterface interface(&model, element);
  203. if (element && data_expression->Run(interface, variant))
  204. {
  205. const String value = variant.Get<String>();
  206. const Property* p = element->GetLocalProperty(property_name);
  207. if (!p || p->Get<String>() != value)
  208. {
  209. element->SetProperty(property_name, value);
  210. result = true;
  211. }
  212. }
  213. return result;
  214. }
  215. StringList DataViewStyle::GetVariableNameList() const {
  216. return data_expression ? data_expression->GetVariableNameList() : StringList();
  217. }
  218. DataViewIf::DataViewIf(DataModel& model, Element* element, const String& binding_name) : DataView(element)
  219. {
  220. data_expression = std::make_unique<DataExpression>(binding_name);
  221. DataVariableInterface interface(&model, element);
  222. if (!data_expression->Parse(interface))
  223. InvalidateView();
  224. }
  225. DataViewIf::~DataViewIf()
  226. {}
  227. bool DataViewIf::Update(DataModel& model)
  228. {
  229. bool result = false;
  230. Variant variant;
  231. Element* element = GetElement();
  232. DataVariableInterface interface(&model, element);
  233. if (element && data_expression->Run(interface, variant))
  234. {
  235. const bool value = variant.Get<bool>();
  236. const bool is_visible = (element->GetLocalStyleProperties().count(PropertyId::Display) == 0);
  237. if(is_visible != value)
  238. {
  239. if (value)
  240. element->RemoveProperty(PropertyId::Display);
  241. else
  242. element->SetProperty(PropertyId::Display, Property(Style::Display::None));
  243. result = true;
  244. }
  245. }
  246. return result;
  247. }
  248. StringList DataViewIf::GetVariableNameList() const {
  249. return data_expression ? data_expression->GetVariableNameList() : StringList();
  250. }
  251. DataViewFor::DataViewFor(DataModel& model, Element* element, const String& in_binding_name, const String& in_rml_content)
  252. : DataView(element), rml_contents(in_rml_content)
  253. {
  254. StringList binding_list;
  255. StringUtilities::ExpandString(binding_list, in_binding_name, ':');
  256. if (binding_list.empty() || binding_list.size() > 2 || binding_list.front().empty() || binding_list.back().empty())
  257. {
  258. Log::Message(Log::LT_WARNING, "Invalid syntax in data-for '%s'", in_binding_name.c_str());
  259. InvalidateView();
  260. return;
  261. }
  262. if (binding_list.size() == 2)
  263. alias_name = binding_list.front();
  264. else
  265. alias_name = "it";
  266. const String& binding_name = binding_list.back();
  267. variable_address = model.ResolveAddress(binding_name, element);
  268. if (variable_address.empty())
  269. {
  270. InvalidateView();
  271. return;
  272. }
  273. attributes = element->GetAttributes();
  274. attributes.erase("data-for");
  275. element->SetProperty(PropertyId::Display, Property(Style::Display::None));
  276. }
  277. bool DataViewFor::Update(DataModel& model)
  278. {
  279. Variable variable = model.GetVariable(variable_address);
  280. if (!variable)
  281. return false;
  282. bool result = false;
  283. const int size = variable.Size();
  284. const int num_elements = (int)elements.size();
  285. Element* element = GetElement();
  286. for (int i = 0; i < Math::Max(size, num_elements); i++)
  287. {
  288. if (i >= num_elements)
  289. {
  290. ElementPtr new_element_ptr = Factory::InstanceElement(nullptr, element->GetTagName(), element->GetTagName(), attributes);
  291. DataAddress replacement_address;
  292. replacement_address.reserve(variable_address.size() + 1);
  293. replacement_address = variable_address;
  294. replacement_address.push_back(AddressEntry(i));
  295. model.InsertAlias(new_element_ptr.get(), alias_name, replacement_address);
  296. Element* new_element = element->GetParentNode()->InsertBefore(std::move(new_element_ptr), element);
  297. elements.push_back(new_element);
  298. elements[i]->SetInnerRML(rml_contents);
  299. RMLUI_ASSERT(i < (int)elements.size());
  300. }
  301. if (i >= size)
  302. {
  303. model.EraseAliases(elements[i]);
  304. elements[i]->GetParentNode()->RemoveChild(elements[i]).reset();
  305. elements[i] = nullptr;
  306. }
  307. }
  308. if (num_elements > size)
  309. elements.resize(size);
  310. return result;
  311. }
  312. DataViews::DataViews()
  313. {}
  314. DataViews::~DataViews()
  315. {}
  316. void DataViews::Add(UniquePtr<DataView> view) {
  317. views_to_add.push_back(std::move(view));
  318. }
  319. void DataViews::OnElementRemove(Element* element)
  320. {
  321. for (auto it = views.begin(); it != views.end();)
  322. {
  323. auto& view = *it;
  324. if (view && view->GetElement() == element)
  325. {
  326. views_to_remove.push_back(std::move(view));
  327. it = views.erase(it);
  328. }
  329. else
  330. ++it;
  331. }
  332. }
  333. bool DataViews::Update(DataModel & model, const SmallUnorderedSet< String >& dirty_variables)
  334. {
  335. bool result = false;
  336. // View updates may result in newly added views, thus we do it recursively but with an upper limit.
  337. // Without the loop, newly added views won't be updated until the next Update() call.
  338. for(int i = 0; i == 0 || (!views_to_add.empty() && i < 10); i++)
  339. {
  340. std::vector<DataView*> dirty_views;
  341. if (!views_to_add.empty())
  342. {
  343. views.reserve(views.size() + views_to_add.size());
  344. for (auto&& view : views_to_add)
  345. {
  346. dirty_views.push_back(view.get());
  347. for (const String& variable_name : view->GetVariableNameList())
  348. name_view_map.emplace(variable_name, view.get());
  349. views.push_back(std::move(view));
  350. }
  351. views_to_add.clear();
  352. }
  353. for (const String& variable_name : dirty_variables)
  354. {
  355. auto pair = name_view_map.equal_range(variable_name);
  356. for (auto it = pair.first; it != pair.second; ++it)
  357. dirty_views.push_back(it->second);
  358. }
  359. // Remove duplicate entries
  360. std::sort(dirty_views.begin(), dirty_views.end());
  361. auto it_remove = std::unique(dirty_views.begin(), dirty_views.end());
  362. dirty_views.erase(it_remove, dirty_views.end());
  363. // Sort by the element's depth in the document tree so that any structural changes due to a changed variable are reflected in the element's children.
  364. // Eg. the 'data-for' view will remove children if any of its data variable array size is reduced.
  365. std::sort(dirty_views.begin(), dirty_views.end(), [](auto&& left, auto&& right) { return left->GetElementDepth() < right->GetElementDepth(); });
  366. for (DataView* view : dirty_views)
  367. {
  368. RMLUI_ASSERT(view);
  369. if (!view)
  370. continue;
  371. if (view->IsValid())
  372. result |= view->Update(model);
  373. }
  374. // Destroy views marked for destruction
  375. // @performance: Horrible...
  376. if (!views_to_remove.empty())
  377. {
  378. for (const auto& view : views_to_remove)
  379. {
  380. for (auto it = name_view_map.begin(); it != name_view_map.end(); )
  381. {
  382. if (it->second == view.get())
  383. it = name_view_map.erase(it);
  384. else
  385. ++it;
  386. }
  387. }
  388. views_to_remove.clear();
  389. }
  390. }
  391. return result;
  392. }
  393. }
  394. }