Element.cpp 81 KB

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