Element.cpp 86 KB

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