Element.cpp 76 KB

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