Element.cpp 86 KB

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