Element.cpp 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693
  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 "../../Include/RmlUi/Core/Element.h"
  29. #include "../../Include/RmlUi/Core/Context.h"
  30. #include "../../Include/RmlUi/Core/Core.h"
  31. #include "../../Include/RmlUi/Core/DataModel.h"
  32. #include "../../Include/RmlUi/Core/ElementDocument.h"
  33. #include "../../Include/RmlUi/Core/ElementInstancer.h"
  34. #include "../../Include/RmlUi/Core/ElementScroll.h"
  35. #include "../../Include/RmlUi/Core/ElementUtilities.h"
  36. #include "../../Include/RmlUi/Core/Factory.h"
  37. #include "../../Include/RmlUi/Core/Dictionary.h"
  38. #include "../../Include/RmlUi/Core/Profiling.h"
  39. #include "../../Include/RmlUi/Core/PropertyIdSet.h"
  40. #include "../../Include/RmlUi/Core/PropertiesIteratorView.h"
  41. #include "../../Include/RmlUi/Core/PropertyDefinition.h"
  42. #include "../../Include/RmlUi/Core/StyleSheetSpecification.h"
  43. #include "../../Include/RmlUi/Core/TransformPrimitive.h"
  44. #include "Clock.h"
  45. #include "ComputeProperty.h"
  46. #include "ElementAnimation.h"
  47. #include "ElementBackgroundBorder.h"
  48. #include "ElementDefinition.h"
  49. #include "ElementStyle.h"
  50. #include "EventDispatcher.h"
  51. #include "EventSpecification.h"
  52. #include "ElementDecoration.h"
  53. #include "LayoutEngine.h"
  54. #include "PluginRegistry.h"
  55. #include "PropertiesIterator.h"
  56. #include "Pool.h"
  57. #include "StyleSheetParser.h"
  58. #include "StyleSheetNode.h"
  59. #include "TransformState.h"
  60. #include "TransformUtilities.h"
  61. #include "XMLParseTools.h"
  62. #include <algorithm>
  63. #include <cmath>
  64. namespace Rml {
  65. /**
  66. STL function object for sorting elements by z-type (ie, float-types before general types, etc).
  67. @author Peter Curry
  68. */
  69. class ElementSortZOrder
  70. {
  71. public:
  72. bool operator()(const Pair< Element*, float >& lhs, const Pair< Element*, float >& rhs) const
  73. {
  74. return lhs.second < rhs.second;
  75. }
  76. };
  77. /**
  78. STL function object for sorting elements by z-index property.
  79. @author Peter Curry
  80. */
  81. class ElementSortZIndex
  82. {
  83. public:
  84. bool operator()(const Element* lhs, const Element* rhs) const
  85. {
  86. // Check the z-index.
  87. return lhs->GetZIndex() < rhs->GetZIndex();
  88. }
  89. };
  90. // Determines how many levels up in the hierarchy the OnChildAdd and OnChildRemove are called (starting at the child itself)
  91. static constexpr int ChildNotifyLevels = 2;
  92. // Meta objects for element collected in a single struct to reduce memory allocations
  93. struct ElementMeta
  94. {
  95. ElementMeta(Element* el) : event_dispatcher(el), style(el), background_border(el), decoration(el), scroll(el) {}
  96. EventDispatcher event_dispatcher;
  97. ElementStyle style;
  98. ElementBackgroundBorder background_border;
  99. ElementDecoration decoration;
  100. ElementScroll scroll;
  101. Style::ComputedValues computed_values;
  102. };
  103. static Pool< ElementMeta > element_meta_chunk_pool(200, true);
  104. /// Constructs a new RmlUi element.
  105. Element::Element(const String& tag) : tag(tag), relative_offset_base(0, 0), relative_offset_position(0, 0), absolute_offset(0, 0), scroll_offset(0, 0), content_offset(0, 0), content_box(0, 0),
  106. transform_state(), dirty_transform(false), dirty_perspective(false), dirty_animation(false), dirty_transition(false)
  107. {
  108. RMLUI_ASSERT(tag == StringUtilities::ToLower(tag));
  109. parent = nullptr;
  110. focus = nullptr;
  111. instancer = nullptr;
  112. owner_document = nullptr;
  113. offset_fixed = false;
  114. offset_parent = nullptr;
  115. offset_dirty = true;
  116. client_area = Box::PADDING;
  117. baseline = 0.0f;
  118. num_non_dom_children = 0;
  119. visible = true;
  120. z_index = 0;
  121. local_stacking_context = false;
  122. local_stacking_context_forced = false;
  123. stacking_context_dirty = false;
  124. structure_dirty = false;
  125. computed_values_are_default_initialized = true;
  126. meta = element_meta_chunk_pool.AllocateAndConstruct(this);
  127. data_model = nullptr;
  128. }
  129. Element::~Element()
  130. {
  131. RMLUI_ASSERT(parent == nullptr);
  132. PluginRegistry::NotifyElementDestroy(this);
  133. // A simplified version of RemoveChild() for destruction.
  134. for (ElementPtr& child : children)
  135. {
  136. Element* child_ancestor = child.get();
  137. for (int i = 0; i <= ChildNotifyLevels && child_ancestor; i++, child_ancestor = child_ancestor->GetParentNode())
  138. child_ancestor->OnChildRemove(child.get());
  139. child->SetParent(nullptr);
  140. }
  141. children.clear();
  142. num_non_dom_children = 0;
  143. element_meta_chunk_pool.DestroyAndDeallocate(meta);
  144. }
  145. void Element::Update(float dp_ratio)
  146. {
  147. #ifdef RMLUI_ENABLE_PROFILING
  148. auto name = GetAddress(false, false);
  149. RMLUI_ZoneScoped;
  150. RMLUI_ZoneText(name.c_str(), name.size());
  151. #endif
  152. OnUpdate();
  153. UpdateStructure();
  154. HandleTransitionProperty();
  155. HandleAnimationProperty();
  156. AdvanceAnimations();
  157. meta->scroll.Update();
  158. UpdateProperties();
  159. // Do en extra pass over the animations and properties if the 'animation' property was just changed.
  160. if (dirty_animation)
  161. {
  162. HandleAnimationProperty();
  163. AdvanceAnimations();
  164. UpdateProperties();
  165. }
  166. for (size_t i = 0; i < children.size(); i++)
  167. children[i]->Update(dp_ratio);
  168. }
  169. void Element::UpdateProperties()
  170. {
  171. meta->style.UpdateDefinition();
  172. if (meta->style.AnyPropertiesDirty())
  173. {
  174. const ComputedValues* parent_values = nullptr;
  175. if (parent)
  176. parent_values = &parent->GetComputedValues();
  177. const ComputedValues* document_values = nullptr;
  178. float dp_ratio = 1.0f;
  179. if (auto doc = GetOwnerDocument())
  180. {
  181. document_values = &doc->GetComputedValues();
  182. if (Context * context = doc->GetContext())
  183. dp_ratio = context->GetDensityIndependentPixelRatio();
  184. }
  185. // Compute values and clear dirty properties
  186. PropertyIdSet dirty_properties = meta->style.ComputeValues(meta->computed_values, parent_values, document_values, computed_values_are_default_initialized, dp_ratio);
  187. computed_values_are_default_initialized = false;
  188. // Computed values are just calculated and can safely be used in OnPropertyChange.
  189. // However, new properties set during this call will not be available until the next update loop.
  190. if (!dirty_properties.Empty())
  191. OnPropertyChange(dirty_properties);
  192. }
  193. }
  194. void Element::Render()
  195. {
  196. #ifdef RMLUI_ENABLE_PROFILING
  197. auto name = GetAddress(false, false);
  198. RMLUI_ZoneScoped;
  199. RMLUI_ZoneText(name.c_str(), name.size());
  200. #endif
  201. // TODO: This is a work-around for the dirty offset not being properly updated when used by (stacking context?) children. This results
  202. // in scrolling not working properly. We don't care about the return value, the call is only used to force the absolute offset to update.
  203. if (offset_dirty)
  204. GetAbsoluteOffset(Box::BORDER);
  205. // Rebuild our stacking context if necessary.
  206. if (stacking_context_dirty)
  207. BuildLocalStackingContext();
  208. UpdateTransformState();
  209. // Render all elements in our local stacking context that have a z-index beneath our local index of 0.
  210. size_t i = 0;
  211. for (; i < stacking_context.size() && stacking_context[i]->z_index < 0; ++i)
  212. stacking_context[i]->Render();
  213. // Apply our transform
  214. ElementUtilities::ApplyTransform(*this);
  215. // Set up the clipping region for this element.
  216. if (ElementUtilities::SetClippingRegion(this))
  217. {
  218. meta->background_border.Render(this);
  219. meta->decoration.RenderDecorators();
  220. {
  221. RMLUI_ZoneScopedNC("OnRender", 0x228B22);
  222. OnRender();
  223. }
  224. }
  225. // Render the rest of the elements in the stacking context.
  226. for (; i < stacking_context.size(); ++i)
  227. stacking_context[i]->Render();
  228. }
  229. // Clones this element, returning a new, unparented element.
  230. ElementPtr Element::Clone() const
  231. {
  232. ElementPtr clone;
  233. if (instancer)
  234. {
  235. clone = instancer->InstanceElement(nullptr, GetTagName(), attributes);
  236. if (clone)
  237. clone->SetInstancer(instancer);
  238. }
  239. else
  240. clone = Factory::InstanceElement(nullptr, GetTagName(), GetTagName(), attributes);
  241. if (clone != nullptr)
  242. {
  243. String inner_rml;
  244. GetInnerRML(inner_rml);
  245. clone->SetInnerRML(inner_rml);
  246. }
  247. return clone;
  248. }
  249. // Sets or removes a class on the element.
  250. void Element::SetClass(const String& class_name, bool activate)
  251. {
  252. meta->style.SetClass(class_name, activate);
  253. }
  254. // Checks if a class is set on the element.
  255. bool Element::IsClassSet(const String& class_name) const
  256. {
  257. return meta->style.IsClassSet(class_name);
  258. }
  259. // Specifies the entire list of classes for this element. This will replace any others specified.
  260. void Element::SetClassNames(const String& class_names)
  261. {
  262. SetAttribute("class", class_names);
  263. }
  264. /// Return the active class list
  265. String Element::GetClassNames() const
  266. {
  267. return meta->style.GetClassNames();
  268. }
  269. // Returns the active style sheet for this element. This may be nullptr.
  270. const SharedPtr<StyleSheet>& Element::GetStyleSheet() const
  271. {
  272. if (ElementDocument * document = GetOwnerDocument())
  273. return document->GetStyleSheet();
  274. static SharedPtr<StyleSheet> null_style_sheet;
  275. return null_style_sheet;
  276. }
  277. // Returns the element's definition.
  278. const ElementDefinition* Element::GetDefinition()
  279. {
  280. return meta->style.GetDefinition();
  281. }
  282. // Fills an String with the full address of this element.
  283. String Element::GetAddress(bool include_pseudo_classes, bool include_parents) const
  284. {
  285. // Add the tag name onto the address.
  286. String address(tag);
  287. // Add the ID if we have one.
  288. if (!id.empty())
  289. {
  290. address += "#";
  291. address += id;
  292. }
  293. String classes = meta->style.GetClassNames();
  294. if (!classes.empty())
  295. {
  296. classes = StringUtilities::Replace(classes, ' ', '.');
  297. address += ".";
  298. address += classes;
  299. }
  300. if (include_pseudo_classes)
  301. {
  302. const PseudoClassList& pseudo_classes = meta->style.GetActivePseudoClasses();
  303. for (PseudoClassList::const_iterator i = pseudo_classes.begin(); i != pseudo_classes.end(); ++i)
  304. {
  305. address += ":";
  306. address += (*i);
  307. }
  308. }
  309. if (include_parents && parent)
  310. {
  311. address += " < ";
  312. return address + parent->GetAddress(include_pseudo_classes, true);
  313. }
  314. else
  315. return address;
  316. }
  317. // Sets the position of this element, as a two-dimensional offset from another element.
  318. void Element::SetOffset(Vector2f offset, Element* _offset_parent, bool _offset_fixed)
  319. {
  320. _offset_fixed |= GetPosition() == Style::Position::Fixed;
  321. // If our offset has definitely changed, or any of our parenting has, then these are set and
  322. // updated based on our left / right / top / bottom properties.
  323. if (relative_offset_base != offset ||
  324. offset_parent != _offset_parent ||
  325. offset_fixed != _offset_fixed)
  326. {
  327. relative_offset_base = offset;
  328. offset_fixed = _offset_fixed;
  329. offset_parent = _offset_parent;
  330. UpdateOffset();
  331. DirtyOffset();
  332. }
  333. // Otherwise, our offset is updated in case left / right / top / bottom will have an impact on
  334. // our final position, and our children are dirtied if they do.
  335. else
  336. {
  337. Vector2f& old_base = relative_offset_base;
  338. Vector2f& old_position = relative_offset_position;
  339. UpdateOffset();
  340. if (old_base != relative_offset_base ||
  341. old_position != relative_offset_position)
  342. DirtyOffset();
  343. }
  344. }
  345. // Returns the position of the top-left corner of one of the areas of this element's primary box.
  346. Vector2f Element::GetRelativeOffset(Box::Area area)
  347. {
  348. return relative_offset_base + relative_offset_position + GetBox().GetPosition(area);
  349. }
  350. // Returns the position of the top-left corner of one of the areas of this element's primary box.
  351. Vector2f Element::GetAbsoluteOffset(Box::Area area)
  352. {
  353. if (offset_dirty)
  354. {
  355. offset_dirty = false;
  356. if (offset_parent != nullptr)
  357. absolute_offset = offset_parent->GetAbsoluteOffset(Box::BORDER) + relative_offset_base + relative_offset_position;
  358. else
  359. absolute_offset = relative_offset_base + relative_offset_position;
  360. // Add any parent scrolling onto our position as well. Could cache this if required.
  361. if (!offset_fixed)
  362. {
  363. Element* scroll_parent = parent;
  364. while (scroll_parent != nullptr)
  365. {
  366. absolute_offset -= (scroll_parent->scroll_offset + scroll_parent->content_offset);
  367. if (scroll_parent == offset_parent)
  368. break;
  369. else
  370. scroll_parent = scroll_parent->parent;
  371. }
  372. }
  373. }
  374. return absolute_offset + GetBox().GetPosition(area);
  375. }
  376. // Sets an alternate area to use as the client area.
  377. void Element::SetClientArea(Box::Area _client_area)
  378. {
  379. client_area = _client_area;
  380. }
  381. // Returns the area the element uses as its client area.
  382. Box::Area Element::GetClientArea() const
  383. {
  384. return client_area;
  385. }
  386. // Sets the dimensions of the element's internal content.
  387. void Element::SetContentBox(Vector2f _content_offset, Vector2f _content_box)
  388. {
  389. if (content_offset != _content_offset ||
  390. content_box != _content_box)
  391. {
  392. // Seems to be jittering a wee bit; might need to be looked at.
  393. scroll_offset.x += (content_offset.x - _content_offset.x);
  394. scroll_offset.y += (content_offset.y - _content_offset.y);
  395. content_offset = _content_offset;
  396. content_box = _content_box;
  397. scroll_offset.x = Math::Min(scroll_offset.x, GetScrollWidth() - GetClientWidth());
  398. scroll_offset.y = Math::Min(scroll_offset.y, GetScrollHeight() - GetClientHeight());
  399. DirtyOffset();
  400. }
  401. }
  402. // Sets the box describing the size of the element.
  403. void Element::SetBox(const Box& box)
  404. {
  405. if (box != main_box || additional_boxes.size() > 0)
  406. {
  407. main_box = box;
  408. additional_boxes.clear();
  409. OnResize();
  410. meta->background_border.DirtyBackground();
  411. meta->background_border.DirtyBorder();
  412. meta->decoration.DirtyDecorators();
  413. }
  414. }
  415. // Adds a box to the end of the list describing this element's geometry.
  416. void Element::AddBox(const Box& box, Vector2f offset)
  417. {
  418. additional_boxes.emplace_back(PositionedBox{ box, offset });
  419. OnResize();
  420. meta->background_border.DirtyBackground();
  421. meta->background_border.DirtyBorder();
  422. meta->decoration.DirtyDecorators();
  423. }
  424. // Returns one of the boxes describing the size of the element.
  425. const Box& Element::GetBox()
  426. {
  427. return main_box;
  428. }
  429. // Returns one of the boxes describing the size of the element.
  430. const Box& Element::GetBox(int index, Vector2f& offset)
  431. {
  432. offset = Vector2f(0);
  433. if (index < 1)
  434. return main_box;
  435. const int additional_box_index = index - 1;
  436. if (additional_box_index >= (int)additional_boxes.size())
  437. return main_box;
  438. offset = additional_boxes[additional_box_index].offset;
  439. return additional_boxes[additional_box_index].box;
  440. }
  441. // Returns the number of boxes making up this element's geometry.
  442. int Element::GetNumBoxes()
  443. {
  444. return 1 + (int)additional_boxes.size();
  445. }
  446. // Returns the baseline of the element, in pixels offset from the bottom of the element's content area.
  447. float Element::GetBaseline() const
  448. {
  449. return baseline;
  450. }
  451. // Gets the intrinsic dimensions of this element, if it is of a type that has an inherent size.
  452. bool Element::GetIntrinsicDimensions(Vector2f& RMLUI_UNUSED_PARAMETER(dimensions), float& RMLUI_UNUSED_PARAMETER(ratio))
  453. {
  454. RMLUI_UNUSED(dimensions);
  455. RMLUI_UNUSED(ratio);
  456. return false;
  457. }
  458. // Checks if a given point in screen coordinates lies within the bordered area of this element.
  459. bool Element::IsPointWithinElement(const Vector2f& point)
  460. {
  461. Vector2f position = GetAbsoluteOffset(Box::BORDER);
  462. for (int i = 0; i < GetNumBoxes(); ++i)
  463. {
  464. Vector2f box_offset;
  465. const Box& box = GetBox(i, box_offset);
  466. const Vector2f box_position = position + box_offset;
  467. const Vector2f box_dimensions = box.GetSize(Box::BORDER);
  468. if (point.x >= box_position.x &&
  469. point.x <= (box_position.x + box_dimensions.x) &&
  470. point.y >= box_position.y &&
  471. point.y <= (box_position.y + box_dimensions.y))
  472. {
  473. return true;
  474. }
  475. }
  476. return false;
  477. }
  478. // Returns the visibility of the element.
  479. bool Element::IsVisible() const
  480. {
  481. return visible;
  482. }
  483. // Returns the z-index of the element.
  484. float Element::GetZIndex() const
  485. {
  486. return z_index;
  487. }
  488. // Returns the element's font face handle.
  489. FontFaceHandle Element::GetFontFaceHandle() const
  490. {
  491. return meta->computed_values.font_face_handle;
  492. }
  493. // Sets a local property override on the element.
  494. bool Element::SetProperty(const String& name, const String& value)
  495. {
  496. // The name may be a shorthand giving us multiple underlying properties
  497. PropertyDictionary properties;
  498. if (!StyleSheetSpecification::ParsePropertyDeclaration(properties, name, value))
  499. {
  500. Log::Message(Log::LT_WARNING, "Syntax error parsing inline property declaration '%s: %s;'.", name.c_str(), value.c_str());
  501. return false;
  502. }
  503. for (auto& property : properties.GetProperties())
  504. {
  505. if (!meta->style.SetProperty(property.first, property.second))
  506. return false;
  507. }
  508. return true;
  509. }
  510. // Sets a local property override on the element to a pre-parsed value.
  511. bool Element::SetProperty(PropertyId id, const Property& property)
  512. {
  513. return meta->style.SetProperty(id, property);
  514. }
  515. // Removes a local property override on the element.
  516. void Element::RemoveProperty(const String& name)
  517. {
  518. meta->style.RemoveProperty(StyleSheetSpecification::GetPropertyId(name));
  519. }
  520. // Removes a local property override on the element.
  521. void Element::RemoveProperty(PropertyId id)
  522. {
  523. meta->style.RemoveProperty(id);
  524. }
  525. // Returns one of this element's properties.
  526. const Property* Element::GetProperty(const String& name)
  527. {
  528. return meta->style.GetProperty(StyleSheetSpecification::GetPropertyId(name));
  529. }
  530. // Returns one of this element's properties.
  531. const Property* Element::GetProperty(PropertyId id)
  532. {
  533. return meta->style.GetProperty(id);
  534. }
  535. // Returns one of this element's properties.
  536. const Property* Element::GetLocalProperty(const String& name)
  537. {
  538. return meta->style.GetLocalProperty(StyleSheetSpecification::GetPropertyId(name));
  539. }
  540. const Property* Element::GetLocalProperty(PropertyId id)
  541. {
  542. return meta->style.GetLocalProperty(id);
  543. }
  544. const PropertyMap& Element::GetLocalStyleProperties()
  545. {
  546. return meta->style.GetLocalStyleProperties();
  547. }
  548. float Element::ResolveNumericProperty(const Property *property, float base_value)
  549. {
  550. return meta->style.ResolveNumericProperty(property, base_value);
  551. }
  552. float Element::ResolveNumericProperty(const String& property_name)
  553. {
  554. auto property = meta->style.GetProperty(StyleSheetSpecification::GetPropertyId(property_name));
  555. if (!property)
  556. return 0.0f;
  557. if (property->unit & Property::ANGLE)
  558. return ComputeAngle(*property);
  559. RelativeTarget relative_target = RelativeTarget::None;
  560. if (property->definition)
  561. relative_target = property->definition->GetRelativeTarget();
  562. float result = meta->style.ResolveLength(property, relative_target);
  563. return result;
  564. }
  565. Vector2f Element::GetContainingBlock()
  566. {
  567. Vector2f containing_block(0, 0);
  568. if (offset_parent != nullptr)
  569. {
  570. using namespace Style;
  571. Position position_property = GetPosition();
  572. const Box& parent_box = offset_parent->GetBox();
  573. if (position_property == Position::Static || position_property == Position::Relative)
  574. {
  575. containing_block = parent_box.GetSize();
  576. }
  577. else if(position_property == Position::Absolute || position_property == Position::Fixed)
  578. {
  579. containing_block = parent_box.GetSize(Box::PADDING);
  580. }
  581. }
  582. return containing_block;
  583. }
  584. Style::Position Element::GetPosition()
  585. {
  586. return meta->computed_values.position;
  587. }
  588. Style::Float Element::GetFloat()
  589. {
  590. return meta->computed_values.float_;
  591. }
  592. Style::Display Element::GetDisplay()
  593. {
  594. return meta->computed_values.display;
  595. }
  596. float Element::GetLineHeight()
  597. {
  598. return meta->computed_values.line_height.value;
  599. }
  600. // Returns this element's TransformState
  601. const TransformState *Element::GetTransformState() const noexcept
  602. {
  603. return transform_state.get();
  604. }
  605. // Project a 2D point in pixel coordinates onto the element's plane.
  606. bool Element::Project(Vector2f& point) const noexcept
  607. {
  608. if(!transform_state || !transform_state->GetTransform())
  609. return true;
  610. // The input point is in window coordinates. Need to find the projection of the point onto the current element plane,
  611. // taking into account the full transform applied to the element.
  612. if (const Matrix4f* inv_transform = transform_state->GetInverseTransform())
  613. {
  614. // Pick two points forming a line segment perpendicular to the window.
  615. Vector4f window_points[2] = {{ point.x, point.y, -10, 1}, { point.x, point.y, 10, 1 }};
  616. // Project them into the local element space.
  617. window_points[0] = *inv_transform * window_points[0];
  618. window_points[1] = *inv_transform * window_points[1];
  619. Vector3f local_points[2] = {
  620. window_points[0].PerspectiveDivide(),
  621. window_points[1].PerspectiveDivide()
  622. };
  623. // Construct a ray from the two projected points in the local space of the current element.
  624. // Find the intersection with the z=0 plane to produce our destination point.
  625. Vector3f ray = local_points[1] - local_points[0];
  626. // Only continue if we are not close to parallel with the plane.
  627. if(std::fabs(ray.z) > 1.0f)
  628. {
  629. // Solving the line equation p = p0 + t*ray for t, knowing that p.z = 0, produces the following.
  630. float t = -local_points[0].z / ray.z;
  631. Vector3f p = local_points[0] + ray * t;
  632. point = Vector2f(p.x, p.y);
  633. return true;
  634. }
  635. }
  636. // The transformation matrix is either singular, or the ray is parallel to the element's plane.
  637. return false;
  638. }
  639. PropertiesIteratorView Element::IterateLocalProperties() const
  640. {
  641. return PropertiesIteratorView(MakeUnique<PropertiesIterator>(meta->style.Iterate()));
  642. }
  643. // Sets or removes a pseudo-class on the element.
  644. void Element::SetPseudoClass(const String& pseudo_class, bool activate)
  645. {
  646. meta->style.SetPseudoClass(pseudo_class, activate);
  647. }
  648. // Checks if a specific pseudo-class has been set on the element.
  649. bool Element::IsPseudoClassSet(const String& pseudo_class) const
  650. {
  651. return meta->style.IsPseudoClassSet(pseudo_class);
  652. }
  653. // Checks if a complete set of pseudo-classes are set on the element.
  654. bool Element::ArePseudoClassesSet(const PseudoClassList& pseudo_classes) const
  655. {
  656. for (PseudoClassList::const_iterator i = pseudo_classes.begin(); i != pseudo_classes.end(); ++i)
  657. {
  658. if (!IsPseudoClassSet(*i))
  659. return false;
  660. }
  661. return true;
  662. }
  663. // Gets a list of the current active pseudo classes
  664. const PseudoClassList& Element::GetActivePseudoClasses() const
  665. {
  666. return meta->style.GetActivePseudoClasses();
  667. }
  668. /// Get the named attribute
  669. Variant* Element::GetAttribute(const String& name)
  670. {
  671. return GetIf(attributes, name);
  672. }
  673. // Checks if the element has a certain attribute.
  674. bool Element::HasAttribute(const String& name) const
  675. {
  676. return attributes.find(name) != attributes.end();
  677. }
  678. // Removes an attribute from the element
  679. void Element::RemoveAttribute(const String& name)
  680. {
  681. auto it = attributes.find(name);
  682. if (it != attributes.end())
  683. {
  684. attributes.erase(it);
  685. ElementAttributes changed_attributes;
  686. changed_attributes.emplace(name, Variant());
  687. OnAttributeChange(changed_attributes);
  688. }
  689. }
  690. // Gets the outer most focus element down the tree from this node
  691. Element* Element::GetFocusLeafNode()
  692. {
  693. // If there isn't a focus, then we are the leaf.
  694. if (!focus)
  695. {
  696. return this;
  697. }
  698. // Recurse down the tree until we found the leaf focus element
  699. Element* focus_element = focus;
  700. while (focus_element->focus)
  701. focus_element = focus_element->focus;
  702. return focus_element;
  703. }
  704. // Returns the element's context.
  705. Context* Element::GetContext() const
  706. {
  707. ElementDocument* document = GetOwnerDocument();
  708. if (document != nullptr)
  709. return document->GetContext();
  710. return nullptr;
  711. }
  712. // Set a group of attributes
  713. void Element::SetAttributes(const ElementAttributes& _attributes)
  714. {
  715. attributes.reserve(attributes.size() + _attributes.size());
  716. for (auto& pair : _attributes)
  717. attributes[pair.first] = pair.second;
  718. OnAttributeChange(_attributes);
  719. }
  720. // Returns the number of attributes on the element.
  721. int Element::GetNumAttributes() const
  722. {
  723. return (int)attributes.size();
  724. }
  725. // Gets the name of the element.
  726. const String& Element::GetTagName() const
  727. {
  728. return tag;
  729. }
  730. // Gets the ID of the element.
  731. const String& Element::GetId() const
  732. {
  733. return id;
  734. }
  735. // Sets the ID of the element.
  736. void Element::SetId(const String& _id)
  737. {
  738. SetAttribute("id", _id);
  739. }
  740. // Gets the horizontal offset from the context's left edge to element's left border edge.
  741. float Element::GetAbsoluteLeft()
  742. {
  743. return GetAbsoluteOffset(Box::BORDER).x;
  744. }
  745. // Gets the vertical offset from the context's top edge to element's top border edge.
  746. float Element::GetAbsoluteTop()
  747. {
  748. return GetAbsoluteOffset(Box::BORDER).y;
  749. }
  750. // Gets the width of the left border of an element.
  751. float Element::GetClientLeft()
  752. {
  753. return GetBox().GetPosition(client_area).x;
  754. }
  755. // Gets the height of the top border of an element.
  756. float Element::GetClientTop()
  757. {
  758. return GetBox().GetPosition(client_area).y;
  759. }
  760. // Gets the inner width of the element.
  761. float Element::GetClientWidth()
  762. {
  763. return GetBox().GetSize(client_area).x - meta->scroll.GetScrollbarSize(ElementScroll::VERTICAL);
  764. }
  765. // Gets the inner height of the element.
  766. float Element::GetClientHeight()
  767. {
  768. return GetBox().GetSize(client_area).y - meta->scroll.GetScrollbarSize(ElementScroll::HORIZONTAL);
  769. }
  770. // Returns the element from which all offset calculations are currently computed.
  771. Element* Element::GetOffsetParent()
  772. {
  773. return offset_parent;
  774. }
  775. // Gets the distance from this element's left border to its offset parent's left border.
  776. float Element::GetOffsetLeft()
  777. {
  778. return relative_offset_base.x + relative_offset_position.x;
  779. }
  780. // Gets the distance from this element's top border to its offset parent's top border.
  781. float Element::GetOffsetTop()
  782. {
  783. return relative_offset_base.y + relative_offset_position.y;
  784. }
  785. // Gets the width of the element, including the client area, padding, borders and scrollbars, but not margins.
  786. float Element::GetOffsetWidth()
  787. {
  788. return GetBox().GetSize(Box::BORDER).x;
  789. }
  790. // Gets the height of the element, including the client area, padding, borders and scrollbars, but not margins.
  791. float Element::GetOffsetHeight()
  792. {
  793. return GetBox().GetSize(Box::BORDER).y;
  794. }
  795. // Gets the left scroll offset of the element.
  796. float Element::GetScrollLeft()
  797. {
  798. return scroll_offset.x;
  799. }
  800. // Sets the left scroll offset of the element.
  801. void Element::SetScrollLeft(float scroll_left)
  802. {
  803. const float new_offset = Math::Clamp(Math::RoundFloat(scroll_left), 0.0f, GetScrollWidth() - GetClientWidth());
  804. if (new_offset != scroll_offset.x)
  805. {
  806. scroll_offset.x = new_offset;
  807. meta->scroll.UpdateScrollbar(ElementScroll::HORIZONTAL);
  808. DirtyOffset();
  809. DispatchEvent(EventId::Scroll, Dictionary());
  810. }
  811. }
  812. // Gets the top scroll offset of the element.
  813. float Element::GetScrollTop()
  814. {
  815. return scroll_offset.y;
  816. }
  817. // Sets the top scroll offset of the element.
  818. void Element::SetScrollTop(float scroll_top)
  819. {
  820. const float new_offset = Math::Clamp(Math::RoundFloat(scroll_top), 0.0f, GetScrollHeight() - GetClientHeight());
  821. if(new_offset != scroll_offset.y)
  822. {
  823. scroll_offset.y = new_offset;
  824. meta->scroll.UpdateScrollbar(ElementScroll::VERTICAL);
  825. DirtyOffset();
  826. DispatchEvent(EventId::Scroll, Dictionary());
  827. }
  828. }
  829. // Gets the width of the scrollable content of the element; it includes the element padding but not its margin.
  830. float Element::GetScrollWidth()
  831. {
  832. return Math::Max(content_box.x, GetClientWidth());
  833. }
  834. // Gets the height of the scrollable content of the element; it includes the element padding but not its margin.
  835. float Element::GetScrollHeight()
  836. {
  837. return Math::Max(content_box.y, GetClientHeight());
  838. }
  839. // Gets the object representing the declarations of an element's style attributes.
  840. ElementStyle* Element::GetStyle() const
  841. {
  842. return &meta->style;
  843. }
  844. // Gets the document this element belongs to.
  845. ElementDocument* Element::GetOwnerDocument() const
  846. {
  847. #ifdef RMLUI_DEBUG
  848. if (parent && !owner_document)
  849. {
  850. // Since we have a parent but no owner_document, then we must be a 'loose' element -- that is, constructed
  851. // outside of a document and not attached to a child of any element in the hierarchy of a document.
  852. // This check ensures that we didn't just forget to set the owner document.
  853. RMLUI_ASSERT(!parent->GetOwnerDocument());
  854. }
  855. #endif
  856. return owner_document;
  857. }
  858. // Gets this element's parent node.
  859. Element* Element::GetParentNode() const
  860. {
  861. return parent;
  862. }
  863. // Gets the element immediately following this one in the tree.
  864. Element* Element::GetNextSibling() const
  865. {
  866. if (parent == nullptr)
  867. return nullptr;
  868. for (size_t i = 0; i < parent->children.size() - (parent->num_non_dom_children + 1); i++)
  869. {
  870. if (parent->children[i].get() == this)
  871. return parent->children[i + 1].get();
  872. }
  873. return nullptr;
  874. }
  875. // Gets the element immediately preceding this one in the tree.
  876. Element* Element::GetPreviousSibling() const
  877. {
  878. if (parent == nullptr)
  879. return nullptr;
  880. for (size_t i = 1; i < parent->children.size() - parent->num_non_dom_children; i++)
  881. {
  882. if (parent->children[i].get() == this)
  883. return parent->children[i - 1].get();
  884. }
  885. return nullptr;
  886. }
  887. // Returns the first child of this element.
  888. Element* Element::GetFirstChild() const
  889. {
  890. if (GetNumChildren() > 0)
  891. return children[0].get();
  892. return nullptr;
  893. }
  894. // Gets the last child of this element.
  895. Element* Element::GetLastChild() const
  896. {
  897. if (GetNumChildren() > 0)
  898. return (children.end() - (num_non_dom_children + 1))->get();
  899. return nullptr;
  900. }
  901. Element* Element::GetChild(int index) const
  902. {
  903. if (index < 0 || index >= (int) children.size())
  904. return nullptr;
  905. return children[index].get();
  906. }
  907. int Element::GetNumChildren(bool include_non_dom_elements) const
  908. {
  909. return (int) children.size() - (include_non_dom_elements ? 0 : num_non_dom_children);
  910. }
  911. // Gets the markup and content of the element.
  912. void Element::GetInnerRML(String& content) const
  913. {
  914. for (int i = 0; i < GetNumChildren(); i++)
  915. {
  916. children[i]->GetRML(content);
  917. }
  918. }
  919. // Gets the markup and content of the element.
  920. String Element::GetInnerRML() const {
  921. String result;
  922. GetInnerRML(result);
  923. return result;
  924. }
  925. // Sets the markup and content of the element. All existing children will be replaced.
  926. void Element::SetInnerRML(const String& rml)
  927. {
  928. RMLUI_ZoneScopedC(0x6495ED);
  929. // Remove all DOM children.
  930. while ((int) children.size() > num_non_dom_children)
  931. RemoveChild(children.front().get());
  932. if(!rml.empty())
  933. Factory::InstanceElementText(this, rml);
  934. }
  935. // Sets the current element as the focus object.
  936. bool Element::Focus()
  937. {
  938. // Are we allowed focus?
  939. Style::Focus focus_property = meta->computed_values.focus;
  940. if (focus_property == Style::Focus::None)
  941. return false;
  942. // Ask our context if we can switch focus.
  943. Context* context = GetContext();
  944. if (context == nullptr)
  945. return false;
  946. if (!context->OnFocusChange(this))
  947. return false;
  948. // Set this as the end of the focus chain.
  949. focus = nullptr;
  950. // Update the focus chain up the hierarchy.
  951. Element* element = this;
  952. while (Element* parent = element->GetParentNode())
  953. {
  954. parent->focus = element;
  955. element = parent;
  956. }
  957. return true;
  958. }
  959. // Removes focus from from this element.
  960. void Element::Blur()
  961. {
  962. if (parent)
  963. {
  964. Context* context = GetContext();
  965. if (context == nullptr)
  966. return;
  967. if (context->GetFocusElement() == this)
  968. {
  969. parent->Focus();
  970. }
  971. else if (parent->focus == this)
  972. {
  973. parent->focus = nullptr;
  974. }
  975. }
  976. }
  977. // Fakes a mouse click on this element.
  978. void Element::Click()
  979. {
  980. Context* context = GetContext();
  981. if (context == nullptr)
  982. return;
  983. context->GenerateClickEvent(this);
  984. }
  985. // Adds an event listener
  986. void Element::AddEventListener(const String& event, EventListener* listener, bool in_capture_phase)
  987. {
  988. EventId id = EventSpecificationInterface::GetIdOrInsert(event);
  989. meta->event_dispatcher.AttachEvent(id, listener, in_capture_phase);
  990. }
  991. // Adds an event listener
  992. void Element::AddEventListener(EventId id, EventListener* listener, bool in_capture_phase)
  993. {
  994. meta->event_dispatcher.AttachEvent(id, listener, in_capture_phase);
  995. }
  996. // Removes an event listener from this element.
  997. void Element::RemoveEventListener(const String& event, EventListener* listener, bool in_capture_phase)
  998. {
  999. EventId id = EventSpecificationInterface::GetIdOrInsert(event);
  1000. meta->event_dispatcher.DetachEvent(id, listener, in_capture_phase);
  1001. }
  1002. // Removes an event listener from this element.
  1003. void Element::RemoveEventListener(EventId id, EventListener* listener, bool in_capture_phase)
  1004. {
  1005. meta->event_dispatcher.DetachEvent(id, listener, in_capture_phase);
  1006. }
  1007. // Dispatches the specified event
  1008. bool Element::DispatchEvent(const String& type, const Dictionary& parameters)
  1009. {
  1010. const EventSpecification& specification = EventSpecificationInterface::GetOrInsert(type);
  1011. return EventDispatcher::DispatchEvent(this, specification.id, type, parameters, specification.interruptible, specification.bubbles, specification.default_action_phase);
  1012. }
  1013. // Dispatches the specified event
  1014. bool Element::DispatchEvent(const String& type, const Dictionary& parameters, bool interruptible, bool bubbles)
  1015. {
  1016. const EventSpecification& specification = EventSpecificationInterface::GetOrInsert(type);
  1017. return EventDispatcher::DispatchEvent(this, specification.id, type, parameters, interruptible, bubbles, specification.default_action_phase);
  1018. }
  1019. // Dispatches the specified event
  1020. bool Element::DispatchEvent(EventId id, const Dictionary& parameters)
  1021. {
  1022. const EventSpecification& specification = EventSpecificationInterface::Get(id);
  1023. return EventDispatcher::DispatchEvent(this, specification.id, specification.type, parameters, specification.interruptible, specification.bubbles, specification.default_action_phase);
  1024. }
  1025. // Scrolls the parent element's contents so that this element is visible.
  1026. void Element::ScrollIntoView(bool align_with_top)
  1027. {
  1028. Vector2f size(0, 0);
  1029. if (!align_with_top)
  1030. size.y = main_box.GetSize(Box::BORDER).y;
  1031. Element* scroll_parent = parent;
  1032. while (scroll_parent != nullptr)
  1033. {
  1034. Style::Overflow overflow_x_property = scroll_parent->GetComputedValues().overflow_x;
  1035. Style::Overflow overflow_y_property = scroll_parent->GetComputedValues().overflow_y;
  1036. if ((overflow_x_property != Style::Overflow::Visible &&
  1037. scroll_parent->GetScrollWidth() > scroll_parent->GetClientWidth()) ||
  1038. (overflow_y_property != Style::Overflow::Visible &&
  1039. scroll_parent->GetScrollHeight() > scroll_parent->GetClientHeight()))
  1040. {
  1041. Vector2f offset = scroll_parent->GetAbsoluteOffset(Box::BORDER) - GetAbsoluteOffset(Box::BORDER);
  1042. Vector2f scroll_offset(scroll_parent->GetScrollLeft(), scroll_parent->GetScrollTop());
  1043. scroll_offset -= offset;
  1044. scroll_offset.x += scroll_parent->GetClientLeft();
  1045. scroll_offset.y += scroll_parent->GetClientTop();
  1046. if (!align_with_top)
  1047. scroll_offset.y -= (scroll_parent->GetClientHeight() - size.y);
  1048. if (overflow_x_property != Style::Overflow::Visible)
  1049. scroll_parent->SetScrollLeft(scroll_offset.x);
  1050. if (overflow_y_property != Style::Overflow::Visible)
  1051. scroll_parent->SetScrollTop(scroll_offset.y);
  1052. }
  1053. scroll_parent = scroll_parent->GetParentNode();
  1054. }
  1055. }
  1056. // Appends a child to this element
  1057. Element* Element::AppendChild(ElementPtr child, bool dom_element)
  1058. {
  1059. RMLUI_ASSERT(child);
  1060. Element* child_ptr = child.get();
  1061. if (dom_element)
  1062. children.insert(children.end() - num_non_dom_children, std::move(child));
  1063. else
  1064. {
  1065. children.push_back(std::move(child));
  1066. num_non_dom_children++;
  1067. }
  1068. // Set parent just after inserting into children. This allows us to eg. get our previous sibling in SetParent.
  1069. child_ptr->SetParent(this);
  1070. Element* ancestor = child_ptr;
  1071. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1072. ancestor->OnChildAdd(child_ptr);
  1073. DirtyStackingContext();
  1074. DirtyStructure();
  1075. if (dom_element)
  1076. DirtyLayout();
  1077. return child_ptr;
  1078. }
  1079. // Adds a child to this element, directly after the adjacent element. Inherits
  1080. // the dom/non-dom status from the adjacent element.
  1081. Element* Element::InsertBefore(ElementPtr child, Element* adjacent_element)
  1082. {
  1083. RMLUI_ASSERT(child);
  1084. // Find the position in the list of children of the adjacent element. If
  1085. // it's nullptr or we can't find it, then we insert it at the end of the dom
  1086. // children, as a dom element.
  1087. size_t child_index = 0;
  1088. bool found_child = false;
  1089. if (adjacent_element)
  1090. {
  1091. for (child_index = 0; child_index < children.size(); child_index++)
  1092. {
  1093. if (children[child_index].get() == adjacent_element)
  1094. {
  1095. found_child = true;
  1096. break;
  1097. }
  1098. }
  1099. }
  1100. Element* child_ptr = nullptr;
  1101. if (found_child)
  1102. {
  1103. child_ptr = child.get();
  1104. if ((int) child_index >= GetNumChildren())
  1105. num_non_dom_children++;
  1106. else
  1107. DirtyLayout();
  1108. children.insert(children.begin() + child_index, std::move(child));
  1109. child_ptr->SetParent(this);
  1110. Element* ancestor = child_ptr;
  1111. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1112. ancestor->OnChildAdd(child_ptr);
  1113. DirtyStackingContext();
  1114. DirtyStructure();
  1115. }
  1116. else
  1117. {
  1118. child_ptr = AppendChild(std::move(child));
  1119. }
  1120. return child_ptr;
  1121. }
  1122. // Replaces the second node with the first node.
  1123. ElementPtr Element::ReplaceChild(ElementPtr inserted_element, Element* replaced_element)
  1124. {
  1125. RMLUI_ASSERT(inserted_element);
  1126. auto insertion_point = children.begin();
  1127. while (insertion_point != children.end() && insertion_point->get() != replaced_element)
  1128. {
  1129. ++insertion_point;
  1130. }
  1131. Element* inserted_element_ptr = inserted_element.get();
  1132. if (insertion_point == children.end())
  1133. {
  1134. AppendChild(std::move(inserted_element));
  1135. return nullptr;
  1136. }
  1137. children.insert(insertion_point, std::move(inserted_element));
  1138. inserted_element_ptr->SetParent(this);
  1139. ElementPtr result = RemoveChild(replaced_element);
  1140. Element* ancestor = inserted_element_ptr;
  1141. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1142. ancestor->OnChildAdd(inserted_element_ptr);
  1143. return result;
  1144. }
  1145. // Removes the specified child
  1146. ElementPtr Element::RemoveChild(Element* child)
  1147. {
  1148. size_t child_index = 0;
  1149. for (auto itr = children.begin(); itr != children.end(); ++itr)
  1150. {
  1151. // Add the element to the delete list
  1152. if (itr->get() == child)
  1153. {
  1154. Element* ancestor = child;
  1155. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1156. ancestor->OnChildRemove(child);
  1157. if (child_index >= children.size() - num_non_dom_children)
  1158. num_non_dom_children--;
  1159. ElementPtr detached_child = std::move(*itr);
  1160. children.erase(itr);
  1161. // Remove the child element as the focused child of this element.
  1162. if (child == focus)
  1163. {
  1164. focus = nullptr;
  1165. // If this child (or a descendant of this child) is the context's currently
  1166. // focused element, set the focus to us instead.
  1167. if (Context * context = GetContext())
  1168. {
  1169. Element* focus_element = context->GetFocusElement();
  1170. while (focus_element)
  1171. {
  1172. if (focus_element == child)
  1173. {
  1174. Focus();
  1175. break;
  1176. }
  1177. focus_element = focus_element->GetParentNode();
  1178. }
  1179. }
  1180. }
  1181. detached_child->SetParent(nullptr);
  1182. DirtyLayout();
  1183. DirtyStackingContext();
  1184. DirtyStructure();
  1185. return detached_child;
  1186. }
  1187. child_index++;
  1188. }
  1189. return nullptr;
  1190. }
  1191. bool Element::HasChildNodes() const
  1192. {
  1193. return (int) children.size() > num_non_dom_children;
  1194. }
  1195. Element* Element::GetElementById(const String& id)
  1196. {
  1197. // Check for special-case tokens.
  1198. if (id == "#self")
  1199. return this;
  1200. else if (id == "#document")
  1201. return GetOwnerDocument();
  1202. else if (id == "#parent")
  1203. return this->parent;
  1204. else
  1205. {
  1206. Element* search_root = GetOwnerDocument();
  1207. if (search_root == nullptr)
  1208. search_root = this;
  1209. return ElementUtilities::GetElementById(search_root, id);
  1210. }
  1211. }
  1212. // Get all elements with the given tag.
  1213. void Element::GetElementsByTagName(ElementList& elements, const String& tag)
  1214. {
  1215. return ElementUtilities::GetElementsByTagName(elements, this, tag);
  1216. }
  1217. // Get all elements with the given class set on them.
  1218. void Element::GetElementsByClassName(ElementList& elements, const String& class_name)
  1219. {
  1220. return ElementUtilities::GetElementsByClassName(elements, this, class_name);
  1221. }
  1222. static Element* QuerySelectorMatchRecursive(const StyleSheetNodeListRaw& nodes, Element* element)
  1223. {
  1224. for (int i = 0; i < element->GetNumChildren(); i++)
  1225. {
  1226. Element* child = element->GetChild(i);
  1227. for (const StyleSheetNode* node : nodes)
  1228. {
  1229. if (node->IsApplicable(child, false))
  1230. return child;
  1231. }
  1232. Element* matching_element = QuerySelectorMatchRecursive(nodes, child);
  1233. if (matching_element)
  1234. return matching_element;
  1235. }
  1236. return nullptr;
  1237. }
  1238. static void QuerySelectorAllMatchRecursive(ElementList& matching_elements, const StyleSheetNodeListRaw& nodes, Element* element)
  1239. {
  1240. for (int i = 0; i < element->GetNumChildren(); i++)
  1241. {
  1242. Element* child = element->GetChild(i);
  1243. for (const StyleSheetNode* node : nodes)
  1244. {
  1245. if (node->IsApplicable(child, false))
  1246. {
  1247. matching_elements.push_back(child);
  1248. break;
  1249. }
  1250. }
  1251. QuerySelectorAllMatchRecursive(matching_elements, nodes, child);
  1252. }
  1253. }
  1254. Element* Element::QuerySelector(const String& selectors)
  1255. {
  1256. StyleSheetNode root_node;
  1257. StyleSheetNodeListRaw leaf_nodes = StyleSheetParser::ConstructNodes(root_node, selectors);
  1258. if (leaf_nodes.empty())
  1259. {
  1260. Log::Message(Log::LT_WARNING, "Query selector '%s' is empty. In element %s", selectors.c_str(), GetAddress().c_str());
  1261. return nullptr;
  1262. }
  1263. return QuerySelectorMatchRecursive(leaf_nodes, this);
  1264. }
  1265. void Element::QuerySelectorAll(ElementList& elements, const String& selectors)
  1266. {
  1267. StyleSheetNode root_node;
  1268. StyleSheetNodeListRaw leaf_nodes = StyleSheetParser::ConstructNodes(root_node, selectors);
  1269. if (leaf_nodes.empty())
  1270. {
  1271. Log::Message(Log::LT_WARNING, "Query selector '%s' is empty. In element %s", selectors.c_str(), GetAddress().c_str());
  1272. return;
  1273. }
  1274. QuerySelectorAllMatchRecursive(elements, leaf_nodes, this);
  1275. }
  1276. // Access the event dispatcher
  1277. EventDispatcher* Element::GetEventDispatcher() const
  1278. {
  1279. return &meta->event_dispatcher;
  1280. }
  1281. String Element::GetEventDispatcherSummary() const
  1282. {
  1283. return meta->event_dispatcher.ToString();
  1284. }
  1285. // Access the element decorators
  1286. ElementDecoration* Element::GetElementDecoration() const
  1287. {
  1288. return &meta->decoration;
  1289. }
  1290. // Returns the element's scrollbar functionality.
  1291. ElementScroll* Element::GetElementScroll() const
  1292. {
  1293. return &meta->scroll;
  1294. }
  1295. DataModel* Element::GetDataModel() const
  1296. {
  1297. return data_model;
  1298. }
  1299. int Element::GetClippingIgnoreDepth()
  1300. {
  1301. return GetComputedValues().clip.number;
  1302. }
  1303. bool Element::IsClippingEnabled()
  1304. {
  1305. const auto& computed = GetComputedValues();
  1306. return computed.overflow_x != Style::Overflow::Visible || computed.overflow_y != Style::Overflow::Visible;
  1307. }
  1308. // Gets the render interface owned by this element's context.
  1309. RenderInterface* Element::GetRenderInterface()
  1310. {
  1311. if (Context* context = GetContext())
  1312. return context->GetRenderInterface();
  1313. return ::Rml::GetRenderInterface();
  1314. }
  1315. void Element::SetInstancer(ElementInstancer* _instancer)
  1316. {
  1317. // Only record the first instancer being set as some instancers call other instancers to do their dirty work, in
  1318. // which case we don't want to update the lowest level instancer.
  1319. if (!instancer)
  1320. {
  1321. instancer = _instancer;
  1322. }
  1323. }
  1324. // Forces the element to generate a local stacking context, regardless of the value of its z-index property.
  1325. void Element::ForceLocalStackingContext()
  1326. {
  1327. local_stacking_context_forced = true;
  1328. local_stacking_context = true;
  1329. DirtyStackingContext();
  1330. }
  1331. // Called during the update loop after children are rendered.
  1332. void Element::OnUpdate()
  1333. {
  1334. }
  1335. // Called during render after backgrounds, borders, decorators, but before children, are rendered.
  1336. void Element::OnRender()
  1337. {
  1338. }
  1339. void Element::OnResize()
  1340. {
  1341. }
  1342. // Called during a layout operation, when the element is being positioned and sized.
  1343. void Element::OnLayout()
  1344. {
  1345. }
  1346. // Called when attributes on the element are changed.
  1347. void Element::OnAttributeChange(const ElementAttributes& changed_attributes)
  1348. {
  1349. auto it = changed_attributes.find("id");
  1350. if (it != changed_attributes.end())
  1351. {
  1352. id = it->second.Get<String>();
  1353. meta->style.DirtyDefinition();
  1354. }
  1355. it = changed_attributes.find("class");
  1356. if (it != changed_attributes.end())
  1357. {
  1358. meta->style.SetClassNames(it->second.Get<String>());
  1359. }
  1360. it = changed_attributes.find("style");
  1361. if (it != changed_attributes.end())
  1362. {
  1363. if (it->second.GetType() == Variant::STRING)
  1364. {
  1365. PropertyDictionary properties;
  1366. StyleSheetParser parser;
  1367. parser.ParseProperties(properties, it->second.GetReference<String>());
  1368. for (const auto& name_value : properties.GetProperties())
  1369. {
  1370. meta->style.SetProperty(name_value.first, name_value.second);
  1371. }
  1372. }
  1373. else if (it->second.GetType() != Variant::NONE)
  1374. {
  1375. Log::Message(Log::LT_WARNING, "Invalid 'style' attribute, string type required. In element: %s", GetAddress().c_str());
  1376. }
  1377. }
  1378. }
  1379. // Called when properties on the element are changed.
  1380. void Element::OnPropertyChange(const PropertyIdSet& changed_properties)
  1381. {
  1382. RMLUI_ZoneScoped;
  1383. if (!IsLayoutDirty())
  1384. {
  1385. // Force a relayout if any of the changed properties require it.
  1386. const PropertyIdSet changed_properties_forcing_layout = (changed_properties & StyleSheetSpecification::GetRegisteredPropertiesForcingLayout());
  1387. if(!changed_properties_forcing_layout.Empty())
  1388. DirtyLayout();
  1389. }
  1390. const bool border_radius_changed = (
  1391. changed_properties.Contains(PropertyId::BorderTopLeftRadius) ||
  1392. changed_properties.Contains(PropertyId::BorderTopRightRadius) ||
  1393. changed_properties.Contains(PropertyId::BorderBottomRightRadius) ||
  1394. changed_properties.Contains(PropertyId::BorderBottomLeftRadius)
  1395. );
  1396. // Update the visibility.
  1397. if (changed_properties.Contains(PropertyId::Visibility) ||
  1398. changed_properties.Contains(PropertyId::Display))
  1399. {
  1400. bool new_visibility = (meta->computed_values.display != Style::Display::None && meta->computed_values.visibility == Style::Visibility::Visible);
  1401. if (visible != new_visibility)
  1402. {
  1403. visible = new_visibility;
  1404. if (parent != nullptr)
  1405. parent->DirtyStackingContext();
  1406. if (!visible)
  1407. Blur();
  1408. }
  1409. if (changed_properties.Contains(PropertyId::Display))
  1410. {
  1411. // Due to structural pseudo-classes, this may change the element definition in siblings and parent.
  1412. // However, the definitions will only be changed on the next update loop which may result in jarring behavior for one @frame.
  1413. // A possible workaround is to add the parent to a list of elements that need to be updated again.
  1414. if (parent != nullptr)
  1415. parent->DirtyStructure();
  1416. }
  1417. }
  1418. // Update the position.
  1419. if (changed_properties.Contains(PropertyId::Left) ||
  1420. changed_properties.Contains(PropertyId::Right) ||
  1421. changed_properties.Contains(PropertyId::Top) ||
  1422. changed_properties.Contains(PropertyId::Bottom))
  1423. {
  1424. // TODO: This should happen during/after layout, as the containing box is not properly defined yet. Off-by-one @frame issue.
  1425. UpdateOffset();
  1426. DirtyOffset();
  1427. }
  1428. // Update the z-index.
  1429. if (changed_properties.Contains(PropertyId::ZIndex))
  1430. {
  1431. Style::ZIndex z_index_property = meta->computed_values.z_index;
  1432. if (z_index_property.type == Style::ZIndex::Auto)
  1433. {
  1434. if (local_stacking_context &&
  1435. !local_stacking_context_forced)
  1436. {
  1437. // We're no longer acting as a stacking context.
  1438. local_stacking_context = false;
  1439. stacking_context_dirty = false;
  1440. stacking_context.clear();
  1441. }
  1442. // If our old z-index was not zero, then we must dirty our stacking context so we'll be re-indexed.
  1443. if (z_index != 0)
  1444. {
  1445. z_index = 0;
  1446. DirtyStackingContext();
  1447. }
  1448. }
  1449. else
  1450. {
  1451. float new_z_index = z_index_property.value;
  1452. if (new_z_index != z_index)
  1453. {
  1454. z_index = new_z_index;
  1455. if (parent != nullptr)
  1456. parent->DirtyStackingContext();
  1457. }
  1458. if (!local_stacking_context)
  1459. {
  1460. local_stacking_context = true;
  1461. stacking_context_dirty = true;
  1462. }
  1463. }
  1464. }
  1465. // Dirty the background if it's changed.
  1466. if (border_radius_changed ||
  1467. changed_properties.Contains(PropertyId::BackgroundColor) ||
  1468. changed_properties.Contains(PropertyId::Opacity) ||
  1469. changed_properties.Contains(PropertyId::ImageColor))
  1470. {
  1471. meta->background_border.DirtyBackground();
  1472. }
  1473. // Dirty the border if it's changed.
  1474. if (border_radius_changed ||
  1475. changed_properties.Contains(PropertyId::BorderTopWidth) ||
  1476. changed_properties.Contains(PropertyId::BorderRightWidth) ||
  1477. changed_properties.Contains(PropertyId::BorderBottomWidth) ||
  1478. changed_properties.Contains(PropertyId::BorderLeftWidth) ||
  1479. changed_properties.Contains(PropertyId::BorderTopColor) ||
  1480. changed_properties.Contains(PropertyId::BorderRightColor) ||
  1481. changed_properties.Contains(PropertyId::BorderBottomColor) ||
  1482. changed_properties.Contains(PropertyId::BorderLeftColor) ||
  1483. changed_properties.Contains(PropertyId::Opacity))
  1484. {
  1485. meta->background_border.DirtyBorder();
  1486. }
  1487. // Dirty the decoration if it's changed.
  1488. if (border_radius_changed ||
  1489. changed_properties.Contains(PropertyId::Decorator) ||
  1490. changed_properties.Contains(PropertyId::Opacity) ||
  1491. changed_properties.Contains(PropertyId::ImageColor))
  1492. {
  1493. meta->decoration.DirtyDecorators();
  1494. }
  1495. // Check for `perspective' and `perspective-origin' changes
  1496. if (changed_properties.Contains(PropertyId::Perspective) ||
  1497. changed_properties.Contains(PropertyId::PerspectiveOriginX) ||
  1498. changed_properties.Contains(PropertyId::PerspectiveOriginY))
  1499. {
  1500. DirtyTransformState(true, false);
  1501. }
  1502. // Check for `transform' and `transform-origin' changes
  1503. if (changed_properties.Contains(PropertyId::Transform) ||
  1504. changed_properties.Contains(PropertyId::TransformOriginX) ||
  1505. changed_properties.Contains(PropertyId::TransformOriginY) ||
  1506. changed_properties.Contains(PropertyId::TransformOriginZ))
  1507. {
  1508. DirtyTransformState(false, true);
  1509. }
  1510. // Check for `animation' changes
  1511. if (changed_properties.Contains(PropertyId::Animation))
  1512. {
  1513. dirty_animation = true;
  1514. }
  1515. // Check for `transition' changes
  1516. if (changed_properties.Contains(PropertyId::Transition))
  1517. {
  1518. dirty_transition = true;
  1519. }
  1520. }
  1521. // Called when a child node has been added somewhere in the hierarchy
  1522. void Element::OnChildAdd(Element* /*child*/)
  1523. {
  1524. }
  1525. // Called when a child node has been removed somewhere in the hierarchy
  1526. void Element::OnChildRemove(Element* /*child*/)
  1527. {
  1528. }
  1529. // Forces a re-layout of this element, and any other children required.
  1530. void Element::DirtyLayout()
  1531. {
  1532. Element* document = GetOwnerDocument();
  1533. if (document != nullptr)
  1534. document->DirtyLayout();
  1535. }
  1536. // Forces a re-layout of this element, and any other children required.
  1537. bool Element::IsLayoutDirty()
  1538. {
  1539. Element* document = GetOwnerDocument();
  1540. if (document != nullptr)
  1541. return document->IsLayoutDirty();
  1542. return false;
  1543. }
  1544. void Element::ProcessDefaultAction(Event& event)
  1545. {
  1546. if (event == EventId::Mousedown && IsPointWithinElement(Vector2f(event.GetParameter< float >("mouse_x", 0), event.GetParameter< float >("mouse_y", 0))) &&
  1547. event.GetParameter< int >("button", 0) == 0)
  1548. SetPseudoClass("active", true);
  1549. if (event == EventId::Mousescroll)
  1550. {
  1551. if (GetScrollHeight() > GetClientHeight())
  1552. {
  1553. Style::Overflow overflow_property = meta->computed_values.overflow_y;
  1554. if (overflow_property == Style::Overflow::Auto ||
  1555. overflow_property == Style::Overflow::Scroll)
  1556. {
  1557. // Stop the propagation if the current element has scrollbars.
  1558. // This prevents scrolling in parent elements, which is often unintended. If instead desired behavior is
  1559. // to scroll in parent elements when reaching top/bottom, move StopPropagation inside the next if statement.
  1560. event.StopPropagation();
  1561. const float wheel_delta = event.GetParameter< float >("wheel_delta", 0.f);
  1562. if ((wheel_delta < 0 && GetScrollTop() > 0) ||
  1563. (wheel_delta > 0 && GetScrollHeight() > GetScrollTop() + GetClientHeight()))
  1564. {
  1565. // Defined as three times the default line-height, multiplied by the dp ratio.
  1566. float default_scroll_length = 3.f * DefaultComputedValues.line_height.value;
  1567. if (const Context* context = GetContext())
  1568. default_scroll_length *= context->GetDensityIndependentPixelRatio();
  1569. SetScrollTop(GetScrollTop() + wheel_delta * default_scroll_length);
  1570. }
  1571. }
  1572. }
  1573. return;
  1574. }
  1575. if (event.GetPhase() == EventPhase::Target)
  1576. {
  1577. switch (event.GetId())
  1578. {
  1579. case EventId::Mouseover:
  1580. SetPseudoClass("hover", true);
  1581. break;
  1582. case EventId::Mouseout:
  1583. SetPseudoClass("hover", false);
  1584. break;
  1585. case EventId::Focus:
  1586. SetPseudoClass("focus", true);
  1587. break;
  1588. case EventId::Blur:
  1589. SetPseudoClass("focus", false);
  1590. break;
  1591. default:
  1592. break;
  1593. }
  1594. }
  1595. }
  1596. const Style::ComputedValues& Element::GetComputedValues() const
  1597. {
  1598. return meta->computed_values;
  1599. }
  1600. void Element::GetRML(String& content)
  1601. {
  1602. // First we start the open tag, add the attributes then close the open tag.
  1603. // Then comes the children in order, then we add our close tag.
  1604. content += "<";
  1605. content += tag;
  1606. for (auto& pair : attributes)
  1607. {
  1608. auto& name = pair.first;
  1609. auto& variant = pair.second;
  1610. String value;
  1611. if (variant.GetInto(value))
  1612. content += " " + name + "=\"" + value + "\"";
  1613. }
  1614. if (HasChildNodes())
  1615. {
  1616. content += ">";
  1617. GetInnerRML(content);
  1618. content += "</";
  1619. content += tag;
  1620. content += ">";
  1621. }
  1622. else
  1623. {
  1624. content += " />";
  1625. }
  1626. }
  1627. void Element::SetOwnerDocument(ElementDocument* document)
  1628. {
  1629. // If this element is a document, then never change owner_document.
  1630. if (owner_document != this)
  1631. {
  1632. if (owner_document && !document)
  1633. {
  1634. // We are detaching from the document and thereby also the context.
  1635. if (Context * context = owner_document->GetContext())
  1636. context->OnElementDetach(this);
  1637. }
  1638. if (owner_document != document)
  1639. {
  1640. owner_document = document;
  1641. for (ElementPtr& child : children)
  1642. child->SetOwnerDocument(document);
  1643. }
  1644. }
  1645. }
  1646. void Element::SetDataModel(DataModel* new_data_model)
  1647. {
  1648. RMLUI_ASSERTMSG(!data_model || !new_data_model, "We must either attach a new data model, or detach the old one.");
  1649. if (data_model == new_data_model)
  1650. return;
  1651. if (data_model)
  1652. data_model->OnElementRemove(this);
  1653. data_model = new_data_model;
  1654. if (data_model)
  1655. ElementUtilities::ApplyDataViewsControllers(this);
  1656. for (ElementPtr& child : children)
  1657. child->SetDataModel(new_data_model);
  1658. }
  1659. void Element::Release()
  1660. {
  1661. if (instancer)
  1662. instancer->ReleaseElement(this);
  1663. else
  1664. Log::Message(Log::LT_WARNING, "Leak detected: element %s not instanced via RmlUi Factory. Unable to release.", GetAddress().c_str());
  1665. }
  1666. void Element::SetParent(Element* _parent)
  1667. {
  1668. // Assumes we are already detached from the hierarchy or we are detaching now.
  1669. RMLUI_ASSERT(!parent || !_parent);
  1670. parent = _parent;
  1671. if (parent)
  1672. {
  1673. // We need to update our definition and make sure we inherit the properties of our new parent.
  1674. meta->style.DirtyDefinition();
  1675. meta->style.DirtyInheritedProperties();
  1676. }
  1677. // The transform state may require recalculation.
  1678. if (transform_state || (parent && parent->transform_state))
  1679. DirtyTransformState(true, true);
  1680. SetOwnerDocument(parent ? parent->GetOwnerDocument() : nullptr);
  1681. if (!parent)
  1682. {
  1683. if (data_model)
  1684. SetDataModel(nullptr);
  1685. }
  1686. else
  1687. {
  1688. auto it = attributes.find("data-model");
  1689. if (it == attributes.end())
  1690. {
  1691. SetDataModel(parent->data_model);
  1692. }
  1693. else if (parent->data_model)
  1694. {
  1695. String name = it->second.Get<String>();
  1696. Log::Message(Log::LT_ERROR, "Nested data models are not allowed. Data model '%s' given in element %s.", name.c_str(), GetAddress().c_str());
  1697. }
  1698. else if (Context* context = GetContext())
  1699. {
  1700. String name = it->second.Get<String>();
  1701. if (DataModel* model = context->GetDataModelPtr(name))
  1702. {
  1703. model->AttachModelRootElement(this);
  1704. SetDataModel(model);
  1705. }
  1706. else
  1707. Log::Message(Log::LT_ERROR, "Could not locate data model '%s' in element %s.", name.c_str(), GetAddress().c_str());
  1708. }
  1709. }
  1710. }
  1711. void Element::DirtyOffset()
  1712. {
  1713. if(!offset_dirty)
  1714. {
  1715. offset_dirty = true;
  1716. if(transform_state)
  1717. DirtyTransformState(true, true);
  1718. // Not strictly true ... ?
  1719. for (size_t i = 0; i < children.size(); i++)
  1720. children[i]->DirtyOffset();
  1721. }
  1722. }
  1723. void Element::UpdateOffset()
  1724. {
  1725. using namespace Style;
  1726. const auto& computed = meta->computed_values;
  1727. Position position_property = computed.position;
  1728. if (position_property == Position::Absolute ||
  1729. position_property == Position::Fixed)
  1730. {
  1731. if (offset_parent != nullptr)
  1732. {
  1733. const Box& parent_box = offset_parent->GetBox();
  1734. Vector2f containing_block = parent_box.GetSize(Box::PADDING);
  1735. // If the element is anchored left, then the position is offset by that resolved value.
  1736. if (computed.left.type != Left::Auto)
  1737. relative_offset_base.x = parent_box.GetEdge(Box::BORDER, Box::LEFT) + (ResolveValue(computed.left, containing_block.x) + GetBox().GetEdge(Box::MARGIN, Box::LEFT));
  1738. // If the element is anchored right, then the position is set first so the element's right-most edge
  1739. // (including margins) will render up against the containing box's right-most content edge, and then
  1740. // offset by the resolved value.
  1741. else if (computed.right.type != Right::Auto)
  1742. relative_offset_base.x = containing_block.x + parent_box.GetEdge(Box::BORDER, Box::LEFT) - (ResolveValue(computed.right, containing_block.x) + GetBox().GetSize(Box::BORDER).x + GetBox().GetEdge(Box::MARGIN, Box::RIGHT));
  1743. // If the element is anchored top, then the position is offset by that resolved value.
  1744. if (computed.top.type != Top::Auto)
  1745. relative_offset_base.y = parent_box.GetEdge(Box::BORDER, Box::TOP) + (ResolveValue(computed.top, containing_block.y) + GetBox().GetEdge(Box::MARGIN, Box::TOP));
  1746. // If the element is anchored bottom, then the position is set first so the element's right-most edge
  1747. // (including margins) will render up against the containing box's right-most content edge, and then
  1748. // offset by the resolved value.
  1749. else if (computed.bottom.type != Bottom::Auto)
  1750. relative_offset_base.y = containing_block.y + parent_box.GetEdge(Box::BORDER, Box::TOP) - (ResolveValue(computed.bottom, containing_block.y) + GetBox().GetSize(Box::BORDER).y + GetBox().GetEdge(Box::MARGIN, Box::BOTTOM));
  1751. }
  1752. }
  1753. else if (position_property == Position::Relative)
  1754. {
  1755. if (offset_parent != nullptr)
  1756. {
  1757. const Box& parent_box = offset_parent->GetBox();
  1758. Vector2f containing_block = parent_box.GetSize();
  1759. if (computed.left.type != Left::Auto)
  1760. relative_offset_position.x = ResolveValue(computed.left, containing_block.x);
  1761. else if (computed.right.type != Right::Auto)
  1762. relative_offset_position.x = -1 * ResolveValue(computed.right, containing_block.x);
  1763. else
  1764. relative_offset_position.x = 0;
  1765. if (computed.top.type != Top::Auto)
  1766. relative_offset_position.y = ResolveValue(computed.top, containing_block.y);
  1767. else if (computed.bottom.type != Bottom::Auto)
  1768. relative_offset_position.y = -1 * ResolveValue(computed.bottom, containing_block.y);
  1769. else
  1770. relative_offset_position.y = 0;
  1771. }
  1772. }
  1773. else
  1774. {
  1775. relative_offset_position.x = 0;
  1776. relative_offset_position.y = 0;
  1777. }
  1778. }
  1779. void Element::SetBaseline(float in_baseline)
  1780. {
  1781. baseline = in_baseline;
  1782. }
  1783. void Element::BuildLocalStackingContext()
  1784. {
  1785. stacking_context_dirty = false;
  1786. stacking_context.clear();
  1787. BuildStackingContext(&stacking_context);
  1788. std::stable_sort(stacking_context.begin(), stacking_context.end(), ElementSortZIndex());
  1789. }
  1790. void Element::BuildStackingContext(ElementList* new_stacking_context)
  1791. {
  1792. RMLUI_ZoneScoped;
  1793. // Build the list of ordered children. Our child list is sorted within the stacking context so stacked elements
  1794. // will render in the right order; ie, positioned elements will render on top of inline elements, which will render
  1795. // on top of floated elements, which will render on top of block elements.
  1796. Vector< Pair< Element*, float > > ordered_children;
  1797. for (size_t i = 0; i < children.size(); ++i)
  1798. {
  1799. Element* child = children[i].get();
  1800. if (!child->IsVisible())
  1801. continue;
  1802. Pair< Element*, float > ordered_child;
  1803. ordered_child.first = child;
  1804. if (child->GetPosition() != Style::Position::Static)
  1805. ordered_child.second = 3;
  1806. else if (child->GetFloat() != Style::Float::None)
  1807. ordered_child.second = 1;
  1808. else if (child->GetDisplay() == Style::Display::Block)
  1809. ordered_child.second = 0;
  1810. else
  1811. ordered_child.second = 2;
  1812. ordered_children.push_back(ordered_child);
  1813. }
  1814. // Sort the list!
  1815. std::stable_sort(ordered_children.begin(), ordered_children.end(), ElementSortZOrder());
  1816. // Add the list of ordered children into the stacking context in order.
  1817. for (size_t i = 0; i < ordered_children.size(); ++i)
  1818. {
  1819. new_stacking_context->push_back(ordered_children[i].first);
  1820. if (!ordered_children[i].first->local_stacking_context)
  1821. ordered_children[i].first->BuildStackingContext(new_stacking_context);
  1822. }
  1823. }
  1824. void Element::DirtyStackingContext()
  1825. {
  1826. // The first ancestor of ours that doesn't have an automatic z-index is the ancestor that is establishing our local
  1827. // stacking context.
  1828. Element* stacking_context_parent = this;
  1829. while (stacking_context_parent != nullptr &&
  1830. !stacking_context_parent->local_stacking_context)
  1831. stacking_context_parent = stacking_context_parent->GetParentNode();
  1832. if (stacking_context_parent != nullptr)
  1833. stacking_context_parent->stacking_context_dirty = true;
  1834. }
  1835. void Element::DirtyStructure()
  1836. {
  1837. structure_dirty = true;
  1838. }
  1839. void Element::UpdateStructure()
  1840. {
  1841. if (structure_dirty)
  1842. {
  1843. structure_dirty = false;
  1844. // If this element or its children depend on structured selectors, they may need to be updated.
  1845. GetStyle()->DirtyDefinition();
  1846. }
  1847. }
  1848. bool Element::Animate(const String & property_name, const Property & target_value, float duration, Tween tween, int num_iterations, bool alternate_direction, float delay, const Property* start_value)
  1849. {
  1850. bool result = false;
  1851. PropertyId property_id = StyleSheetSpecification::GetPropertyId(property_name);
  1852. auto it_animation = StartAnimation(property_id, start_value, num_iterations, alternate_direction, delay, false);
  1853. if (it_animation != animations.end())
  1854. {
  1855. result = it_animation->AddKey(duration, target_value, *this, tween, true);
  1856. if (!result)
  1857. animations.erase(it_animation);
  1858. }
  1859. return result;
  1860. }
  1861. bool Element::AddAnimationKey(const String & property_name, const Property & target_value, float duration, Tween tween)
  1862. {
  1863. ElementAnimation* animation = nullptr;
  1864. PropertyId property_id = StyleSheetSpecification::GetPropertyId(property_name);
  1865. for (auto& existing_animation : animations) {
  1866. if (existing_animation.GetPropertyId() == property_id) {
  1867. animation = &existing_animation;
  1868. break;
  1869. }
  1870. }
  1871. if (!animation)
  1872. return false;
  1873. bool result = animation->AddKey(animation->GetDuration() + duration, target_value, *this, tween, true);
  1874. return result;
  1875. }
  1876. ElementAnimationList::iterator Element::StartAnimation(PropertyId property_id, const Property* start_value, int num_iterations, bool alternate_direction, float delay, bool initiated_by_animation_property)
  1877. {
  1878. auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyId() == property_id; });
  1879. if (it != animations.end())
  1880. {
  1881. *it = ElementAnimation{};
  1882. }
  1883. else
  1884. {
  1885. animations.emplace_back();
  1886. it = animations.end() - 1;
  1887. }
  1888. Property value;
  1889. if (start_value)
  1890. {
  1891. value = *start_value;
  1892. if (!value.definition)
  1893. if(auto default_value = GetProperty(property_id))
  1894. value.definition = default_value->definition;
  1895. }
  1896. else if (auto default_value = GetProperty(property_id))
  1897. {
  1898. value = *default_value;
  1899. }
  1900. if (value.definition)
  1901. {
  1902. ElementAnimationOrigin origin = (initiated_by_animation_property ? ElementAnimationOrigin::Animation : ElementAnimationOrigin::User);
  1903. double start_time = Clock::GetElapsedTime() + (double)delay;
  1904. *it = ElementAnimation{ property_id, origin, value, *this, start_time, 0.0f, num_iterations, alternate_direction };
  1905. }
  1906. if(!it->IsInitalized())
  1907. {
  1908. animations.erase(it);
  1909. it = animations.end();
  1910. }
  1911. return it;
  1912. }
  1913. bool Element::AddAnimationKeyTime(PropertyId property_id, const Property* target_value, float time, Tween tween)
  1914. {
  1915. if (!target_value)
  1916. target_value = meta->style.GetProperty(property_id);
  1917. if (!target_value)
  1918. return false;
  1919. ElementAnimation* animation = nullptr;
  1920. for (auto& existing_animation : animations) {
  1921. if (existing_animation.GetPropertyId() == property_id) {
  1922. animation = &existing_animation;
  1923. break;
  1924. }
  1925. }
  1926. if (!animation)
  1927. return false;
  1928. bool result = animation->AddKey(time, *target_value, *this, tween, true);
  1929. return result;
  1930. }
  1931. bool Element::StartTransition(const Transition & transition, const Property& start_value, const Property & target_value)
  1932. {
  1933. auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyId() == transition.id; });
  1934. if (it != animations.end() && !it->IsTransition())
  1935. return false;
  1936. float duration = transition.duration;
  1937. double start_time = Clock::GetElapsedTime() + (double)transition.delay;
  1938. if (it == animations.end())
  1939. {
  1940. // Add transition as new animation
  1941. animations.push_back(
  1942. ElementAnimation{ transition.id, ElementAnimationOrigin::Transition, start_value, *this, start_time, 0.0f, 1, false }
  1943. );
  1944. it = (animations.end() - 1);
  1945. }
  1946. else
  1947. {
  1948. // Compress the duration based on the progress of the current animation
  1949. float f = it->GetInterpolationFactor();
  1950. f = 1.0f - (1.0f - f)*transition.reverse_adjustment_factor;
  1951. duration = duration * f;
  1952. // Replace old transition
  1953. *it = ElementAnimation{ transition.id, ElementAnimationOrigin::Transition, start_value, *this, start_time, 0.0f, 1, false };
  1954. }
  1955. bool result = it->AddKey(duration, target_value, *this, transition.tween, true);
  1956. if (result)
  1957. SetProperty(transition.id, start_value);
  1958. else
  1959. animations.erase(it);
  1960. return result;
  1961. }
  1962. void Element::HandleTransitionProperty()
  1963. {
  1964. if(dirty_transition)
  1965. {
  1966. dirty_transition = false;
  1967. // Remove all transitions that are no longer in our local list
  1968. const TransitionList& keep_transitions = GetComputedValues().transition;
  1969. if (keep_transitions.all)
  1970. return;
  1971. auto it_remove = animations.end();
  1972. if (keep_transitions.none)
  1973. {
  1974. // All transitions should be removed, but only touch the animations that originate from the 'transition' property.
  1975. // Move all animations to be erased in a valid state at the end of the list, and erase later.
  1976. it_remove = std::partition(animations.begin(), animations.end(),
  1977. [](const ElementAnimation& animation) -> bool { return !animation.IsTransition(); }
  1978. );
  1979. }
  1980. else
  1981. {
  1982. // Only remove the transitions that are not in our keep list.
  1983. const auto& keep_transitions_list = keep_transitions.transitions;
  1984. it_remove = std::partition(animations.begin(), animations.end(),
  1985. [&keep_transitions_list](const ElementAnimation& animation) -> bool {
  1986. if (!animation.IsTransition())
  1987. return true;
  1988. auto it = std::find_if(keep_transitions_list.begin(), keep_transitions_list.end(),
  1989. [&animation](const Transition& transition) { return animation.GetPropertyId() == transition.id; }
  1990. );
  1991. bool keep_animation = (it != keep_transitions_list.end());
  1992. return keep_animation;
  1993. }
  1994. );
  1995. }
  1996. // We can decide what to do with cancelled transitions here.
  1997. for (auto it = it_remove; it != animations.end(); ++it)
  1998. RemoveProperty(it->GetPropertyId());
  1999. animations.erase(it_remove, animations.end());
  2000. }
  2001. }
  2002. void Element::HandleAnimationProperty()
  2003. {
  2004. // Note: We are effectively restarting all animations whenever 'dirty_animation' is set. Use the dirty flag with care,
  2005. // or find another approach which only updates actual "dirty" animations.
  2006. if (dirty_animation)
  2007. {
  2008. dirty_animation = false;
  2009. const AnimationList& animation_list = meta->computed_values.animation;
  2010. bool element_has_animations = (!animation_list.empty() || !animations.empty());
  2011. StyleSheet* stylesheet = nullptr;
  2012. if (element_has_animations)
  2013. stylesheet = GetStyleSheet().get();
  2014. if (stylesheet)
  2015. {
  2016. // Remove existing animations
  2017. {
  2018. // We only touch the animations that originate from the 'animation' property.
  2019. auto it_remove = std::partition(animations.begin(), animations.end(),
  2020. [](const ElementAnimation & animation) { return animation.GetOrigin() != ElementAnimationOrigin::Animation; }
  2021. );
  2022. // We can decide what to do with cancelled animations here.
  2023. for (auto it = it_remove; it != animations.end(); ++it)
  2024. RemoveProperty(it->GetPropertyId());
  2025. animations.erase(it_remove, animations.end());
  2026. }
  2027. // Start animations
  2028. for (const auto& animation : animation_list)
  2029. {
  2030. const Keyframes* keyframes_ptr = stylesheet->GetKeyframes(animation.name);
  2031. if (keyframes_ptr && keyframes_ptr->blocks.size() >= 1 && !animation.paused)
  2032. {
  2033. auto& property_ids = keyframes_ptr->property_ids;
  2034. auto& blocks = keyframes_ptr->blocks;
  2035. bool has_from_key = (blocks[0].normalized_time == 0);
  2036. bool has_to_key = (blocks.back().normalized_time == 1);
  2037. // If the first key defines initial conditions for a given property, use those values, else, use this element's current values.
  2038. for (PropertyId id : property_ids)
  2039. StartAnimation(id, (has_from_key ? blocks[0].properties.GetProperty(id) : nullptr), animation.num_iterations, animation.alternate, animation.delay, true);
  2040. // Add middle keys: Need to skip the first and last keys if they set the initial and end conditions, respectively.
  2041. for (int i = (has_from_key ? 1 : 0); i < (int)blocks.size() + (has_to_key ? -1 : 0); i++)
  2042. {
  2043. // Add properties of current key to animation
  2044. float time = blocks[i].normalized_time * animation.duration;
  2045. for (auto& property : blocks[i].properties.GetProperties())
  2046. AddAnimationKeyTime(property.first, &property.second, time, animation.tween);
  2047. }
  2048. // If the last key defines end conditions for a given property, use those values, else, use this element's current values.
  2049. float time = animation.duration;
  2050. for (PropertyId id : property_ids)
  2051. AddAnimationKeyTime(id, (has_to_key ? blocks.back().properties.GetProperty(id) : nullptr), time, animation.tween);
  2052. }
  2053. }
  2054. }
  2055. }
  2056. }
  2057. void Element::AdvanceAnimations()
  2058. {
  2059. if (!animations.empty())
  2060. {
  2061. double time = Clock::GetElapsedTime();
  2062. for (auto& animation : animations)
  2063. {
  2064. Property property = animation.UpdateAndGetProperty(time, *this);
  2065. if (property.unit != Property::UNKNOWN)
  2066. SetProperty(animation.GetPropertyId(), property);
  2067. }
  2068. // Move all completed animations to the end of the list
  2069. auto it_completed = std::partition(animations.begin(), animations.end(), [](const ElementAnimation& animation) { return !animation.IsComplete(); });
  2070. Vector<Dictionary> dictionary_list;
  2071. Vector<bool> is_transition;
  2072. dictionary_list.reserve(animations.end() - it_completed);
  2073. is_transition.reserve(animations.end() - it_completed);
  2074. for (auto it = it_completed; it != animations.end(); ++it)
  2075. {
  2076. const String& property_name = StyleSheetSpecification::GetPropertyName(it->GetPropertyId());
  2077. dictionary_list.emplace_back();
  2078. dictionary_list.back().emplace("property", Variant(property_name));
  2079. is_transition.push_back(it->IsTransition());
  2080. // Remove completed transition- and animation-initiated properties.
  2081. // Should behave like in HandleTransitionProperty() and HandleAnimationProperty() respectively.
  2082. if (it->GetOrigin() != ElementAnimationOrigin::User)
  2083. RemoveProperty(it->GetPropertyId());
  2084. }
  2085. // Need to erase elements before submitting event, as iterators might be invalidated when calling external code.
  2086. animations.erase(it_completed, animations.end());
  2087. for (size_t i = 0; i < dictionary_list.size(); i++)
  2088. DispatchEvent(is_transition[i] ? EventId::Transitionend : EventId::Animationend, dictionary_list[i]);
  2089. }
  2090. }
  2091. void Element::DirtyTransformState(bool perspective_dirty, bool transform_dirty)
  2092. {
  2093. dirty_perspective |= perspective_dirty;
  2094. dirty_transform |= transform_dirty;
  2095. }
  2096. void Element::UpdateTransformState()
  2097. {
  2098. if (!dirty_perspective && !dirty_transform)
  2099. return;
  2100. const ComputedValues& computed = meta->computed_values;
  2101. const Vector2f pos = GetAbsoluteOffset(Box::BORDER);
  2102. const Vector2f size = GetBox().GetSize(Box::BORDER);
  2103. bool perspective_or_transform_changed = false;
  2104. if (dirty_perspective)
  2105. {
  2106. // If perspective is set on this element, then it applies to our children. We just calculate it here,
  2107. // and let the children's transform update merge it with their transform.
  2108. bool had_perspective = (transform_state && transform_state->GetLocalPerspective());
  2109. float distance = computed.perspective;
  2110. Vector2f vanish = Vector2f(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f);
  2111. bool have_perspective = false;
  2112. if (distance > 0.0f)
  2113. {
  2114. have_perspective = true;
  2115. // Compute the vanishing point from the perspective origin
  2116. if (computed.perspective_origin_x.type == Style::PerspectiveOrigin::Percentage)
  2117. vanish.x = pos.x + computed.perspective_origin_x.value * 0.01f * size.x;
  2118. else
  2119. vanish.x = pos.x + computed.perspective_origin_x.value;
  2120. if (computed.perspective_origin_y.type == Style::PerspectiveOrigin::Percentage)
  2121. vanish.y = pos.y + computed.perspective_origin_y.value * 0.01f * size.y;
  2122. else
  2123. vanish.y = pos.y + computed.perspective_origin_y.value;
  2124. }
  2125. if (have_perspective)
  2126. {
  2127. // Equivalent to: Translate(x,y,0) * Perspective(distance) * Translate(-x,-y,0)
  2128. Matrix4f perspective = Matrix4f::FromRows(
  2129. { 1, 0, -vanish.x / distance, 0 },
  2130. { 0, 1, -vanish.y / distance, 0 },
  2131. { 0, 0, 1, 0 },
  2132. { 0, 0, -1 / distance, 1 }
  2133. );
  2134. if (!transform_state)
  2135. transform_state = MakeUnique<TransformState>();
  2136. perspective_or_transform_changed |= transform_state->SetLocalPerspective(&perspective);
  2137. }
  2138. else if (transform_state)
  2139. transform_state->SetLocalPerspective(nullptr);
  2140. perspective_or_transform_changed |= (have_perspective != had_perspective);
  2141. dirty_perspective = false;
  2142. }
  2143. if (dirty_transform)
  2144. {
  2145. // We want to find the accumulated transform given all our ancestors. It is assumed here that the parent transform is already updated,
  2146. // so that we only need to consider our local transform and combine it with our parent's transform and perspective matrices.
  2147. bool had_transform = (transform_state && transform_state->GetTransform());
  2148. bool have_transform = false;
  2149. Matrix4f transform = Matrix4f::Identity();
  2150. if (computed.transform)
  2151. {
  2152. // First find the current element's transform
  2153. const int n = computed.transform->GetNumPrimitives();
  2154. for (int i = 0; i < n; ++i)
  2155. {
  2156. const TransformPrimitive& primitive = computed.transform->GetPrimitive(i);
  2157. Matrix4f matrix = TransformUtilities::ResolveTransform(primitive, *this);
  2158. transform *= matrix;
  2159. have_transform = true;
  2160. }
  2161. if(have_transform)
  2162. {
  2163. // Compute the transform origin
  2164. Vector3f transform_origin(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f, 0);
  2165. if (computed.transform_origin_x.type == Style::TransformOrigin::Percentage)
  2166. transform_origin.x = pos.x + computed.transform_origin_x.value * size.x * 0.01f;
  2167. else
  2168. transform_origin.x = pos.x + computed.transform_origin_x.value;
  2169. if (computed.transform_origin_y.type == Style::TransformOrigin::Percentage)
  2170. transform_origin.y = pos.y + computed.transform_origin_y.value * size.y * 0.01f;
  2171. else
  2172. transform_origin.y = pos.y + computed.transform_origin_y.value;
  2173. transform_origin.z = computed.transform_origin_z;
  2174. // Make the transformation apply relative to the transform origin
  2175. transform = Matrix4f::Translate(transform_origin) * transform * Matrix4f::Translate(-transform_origin);
  2176. }
  2177. // We may want to include the local offsets here, as suggested by the CSS specs, so that the local transform is applied after the offset I believe
  2178. // the motivation is. Then we would need to subtract the absolute zero-offsets during geometry submit whenever we have transforms.
  2179. }
  2180. if (parent && parent->transform_state)
  2181. {
  2182. // Apply the parent's local perspective and transform.
  2183. // @performance: If we have no local transform and no parent perspective, we can effectively just point to the parent transform instead of copying it.
  2184. const TransformState& parent_state = *parent->transform_state;
  2185. if (auto parent_perspective = parent_state.GetLocalPerspective())
  2186. {
  2187. transform = *parent_perspective * transform;
  2188. have_transform = true;
  2189. }
  2190. if (auto parent_transform = parent_state.GetTransform())
  2191. {
  2192. transform = *parent_transform * transform;
  2193. have_transform = true;
  2194. }
  2195. }
  2196. if (have_transform)
  2197. {
  2198. if (!transform_state)
  2199. transform_state = MakeUnique<TransformState>();
  2200. perspective_or_transform_changed |= transform_state->SetTransform(&transform);
  2201. }
  2202. else if (transform_state)
  2203. transform_state->SetTransform(nullptr);
  2204. perspective_or_transform_changed |= (had_transform != have_transform);
  2205. }
  2206. // A change in perspective or transform will require an update to children transforms as well.
  2207. if (perspective_or_transform_changed)
  2208. {
  2209. for (size_t i = 0; i < children.size(); i++)
  2210. children[i]->DirtyTransformState(false, true);
  2211. }
  2212. // No reason to keep the transform state around if transform and perspective have been removed.
  2213. if (transform_state && !transform_state->GetTransform() && !transform_state->GetLocalPerspective())
  2214. {
  2215. transform_state.reset();
  2216. }
  2217. }
  2218. } // namespace Rml