Element.cpp 82 KB

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