2
0

Element.cpp 85 KB

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